Created
May 7, 2020 06:47
-
-
Save amir-arad/4fc94bcf65338fc1bcdf89e82af6fab9 to your computer and use it in GitHub Desktop.
deterministic RSA keys
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 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