I am using WebCrypto with RSASSA-PKCS1-v1_5 (https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---sign) and I need to export the public key to PEM format using javascript code.
The documentation says that is possible to export the key in this way: https://github.com/diafygi/webcrypto-examples#rsassa-pkcs1-v1_5---exportkey but I need a different format.
Any idea?
Thanks in advance.
Regards
Export the public key to spki
window.crypto.subtle.exportKey("spki",keys.publicKey);
And convert the resulting array buffer to base64 adding the PEM headers -----BEGIN PUBLIC KEY-----
and -----END PUBLIC KEY-----
. Below I provide the function spkiToPEM
with a full example
crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"},
},
false,
["sign", "verify"]
).then(function(keys){
return window.crypto.subtle.exportKey("spki",keys.publicKey);
}).then (function(keydata){
var pem = spkiToPEM(keydata);
console.log(pem);
}).catch(function(err){
console.error(err);
});
function spkiToPEM(keydata){
var keydataS = arrayBufferToString(keydata);
var keydataB64 = window.btoa(keydataS);
var keydataB64Pem = formatAsPem(keydataB64);
return keydataB64Pem;
}
function arrayBufferToString( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return binary;
}
function formatAsPem(str) {
var finalString = '-----BEGIN PUBLIC KEY-----\n';
while(str.length > 0) {
finalString += str.substring(0, 64) + '\n';
str = str.substring(64);
}
finalString = finalString + "-----END PUBLIC KEY-----";
return finalString;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With