Generating RSA key pair and converting to PEM format
suggest changeThis browser example generates an RSA-OAEP key pair and writes the private key as a PKCS#8 PEM block (BEGIN PRIVATE KEY). A public key is a different export: exportKey("spki", keyPair.publicKey) and the BEGIN PUBLIC KEY / END PUBLIC KEY labels. Swapping only the labels while still exporting "pkcs8" does not produce a public key. Current browsers reject a modulusLength below 2048. Node's crypto.subtle can run the same calls without window.
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
NOTE: This example is fully tested in these browsers: Chrome, Firefox, Opera, Vivaldi
function arrayBufferToBase64(arrayBuffer) {
const byteArray = new Uint8Array(arrayBuffer);
let byteString = '';
for(let i=0; i < byteArray.byteLength; i++) {
byteString += String.fromCharCode(byteArray[i]);
}
const b64 = window.btoa(byteString);
return b64;
}
function addNewLines(str) {
let finalString = '';
while(str.length > 0) {
finalString += str.substring(0, 64) + '\n';
str = str.substring(64);
}
return finalString;
}
function toPem(privateKey) {
const b64 = addNewLines(arrayBufferToBase64(privateKey));
const pem = "-----BEGIN PRIVATE KEY-----\n" + b64 + "-----END PRIVATE KEY-----";
return pem;
}
// Let's generate the key pair first
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048, // 2048 or 4096; 1024 is rejected
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"} // or SHA-512
},
true,
["encrypt", "decrypt"]
).then(function(keyPair) {
/* now when the key pair is generated we are going
to export it from the keypair object in pkcs8
*/
window.crypto.subtle.exportKey(
"pkcs8",
keyPair.privateKey
).then(function(exportedPrivateKey) {
// converting exported private key to PEM format
const pem = toPem(exportedPrivateKey);
console.log(pem);
}).catch(function(err) {
console.log(err);
});
});
That’s it! Now you have a fully working and compatible RSA-OAEP Private Key in PEM format which you can use wherever you want. Enjoy!
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents