Skip to content

Instantly share code, notes, and snippets.

@amir-arad
Created May 7, 2020 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amir-arad/4fc94bcf65338fc1bcdf89e82af6fab9 to your computer and use it in GitHub Desktop.
Save amir-arad/4fc94bcf65338fc1bcdf89e82af6fab9 to your computer and use it in GitHub Desktop.
deterministic RSA keys
const forge = require('node-forge');
const rsa = forge.pki.rsa;
function fix (str) {
return str.replace(/\r/g, '') + '\n'
}
exports.makeKey = function makeKey(id){
const prng = {
getBytesSync(_length){
const _id = '_' + id;
return {
charCodeAt(i){
return _id.charCodeAt(i % id.length);
}
};
}
};
return new Promise(res => {
// generate an RSA key pair in steps that attempt to run for a specified period
// of time on the main JS thread
var state = rsa.createKeyPairGenerationState(2048, 0x10001, {prng});
var step = function() {
// run for 100 ms
if(!rsa.stepKeyPairGenerationState(state, 100)) {
setTimeout(step, 1);
}
else {
// done, turn off progress indicator, use state.keys
// res(state.keys);
res({
publicKeyArmored: fix(forge.pki.publicKeyToRSAPublicKeyPem(state.keys.publicKey, 72)),
privateKeyArmored: fix(forge.pki.privateKeyToPem(state.keys.privateKey, 72))
});
}
};
// turn on progress indicator, schedule generation to run
setTimeout(step, 1);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment