Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export webcrypto key to PEM format

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

like image 599
Seba Avatar asked Dec 04 '22 23:12

Seba


1 Answers

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;
}
like image 62
pedrofb Avatar answered Dec 21 '22 22:12

pedrofb