Skip to content

Instantly share code, notes, and snippets.

@jm42
Created April 10, 2021 21:29
Show Gist options
  • Save jm42/5bd6b0936f69958b7b17d9b19b01f5ab to your computer and use it in GitHub Desktop.
Save jm42/5bd6b0936f69958b7b17d9b19b01f5ab to your computer and use it in GitHub Desktop.
Generate RSA key per canvas
module.exports = Object.freeze({
/** RSA bits for key pair generation */
KEY_BITS: 512,
})
const { KeyObject } = require('crypto')
const generateKeyPair = require('./generateKeyPair')
module.exports = async (state, canvasId, keyName, passphrase) => {
if (keyName !== 'privateKey' && keyName !== 'publicKey') {
throw new Error(`Invalid key ${keyName}`)
}
let key = await state.get(`${canvasId}:${keyName}`)
if (key) {
//key = KeyObject.from(key)
} else {
const keys = generateKeyPair(state, canvasId, passphrase)
key = keys[keyName]
}
return key
}
const { generateKeyPair } = require('crypto')
const { KEY_BITS } = require('./constants')
async function generateCanvasKeyPair(canvasId, passphrase) {
return new Promise((resolve, reject) => {
generateKeyPair('rsa', {
modulusLength: KEY_BITS,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: `${canvasId}:${passphrase}`
}
}, (err, publicKey, privateKey) => {
console.log(publicKey, privateKey)
if (err) {
reject(err)
} else {
resolve({ publicKey, privateKey })
}
})
})
}
module.exports = async (state, canvasId, passphrase) => {
const keys = await generateCanvasKeyPair(canvasId, passphrase)
Object.keys(keys).forEach(async (generatedKeyName) => {
await state.set(`${canvasId}:${generatedKeyName}`, keys[generatedKeyName])
})
return keys
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment