Created
April 10, 2021 21:29
-
-
Save jm42/5bd6b0936f69958b7b17d9b19b01f5ab to your computer and use it in GitHub Desktop.
Generate RSA key per canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = Object.freeze({ | |
/** RSA bits for key pair generation */ | |
KEY_BITS: 512, | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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