Converting PEM key pair to CryptoKey

suggest change

This page shows how to import an OpenSSL PEM RSA key into the Web Cryptography API. yourprivatekey below is a placeholder for that PEM text. The example is browser-only (window.atob and window.crypto.subtle).

atob rejects whitespace, and replace("\n", "") removes only the first newline. Strip every whitespace character. The header must match the key: a PKCS#8 block is BEGIN PRIVATE KEY, imported as "pkcs8". OpenSSL’s BEGIN RSA PRIVATE KEY is PKCS#1 and will not import as "pkcs8". A public BEGIN PUBLIC KEY block is imported as "spki", not by swapping only the strings inside pemToArrayBuffer while leaving "pkcs8" in place.

function removeLines(str) {
    return str.replace(/\s/g, "");
}

function base64ToArrayBuffer(b64) {
    const byteString = window.atob(b64);
    const byteArray = new Uint8Array(byteString.length);
    for(let i=0; i < byteString.length; i++) {
        byteArray[i] = byteString.charCodeAt(i);
    }

    return byteArray;
}

function pemToArrayBuffer(pem) {
    const b64Lines = removeLines(pem);
    const b64Prefix = b64Lines.replace('-----BEGIN PRIVATE KEY-----', '');
    const b64Final = b64Prefix.replace('-----END PRIVATE KEY-----', '');

    return base64ToArrayBuffer(b64Final);
}

window.crypto.subtle.importKey(
    "pkcs8",
    pemToArrayBuffer(yourprivatekey),
    {
        name: "RSA-OAEP",
        hash: {name: "SHA-256"} // or SHA-512
    },
    true,
    ["decrypt"]
).then(function(importedPrivateKey) {
    console.log(importedPrivateKey);
}).catch(function(err) {
    console.log(err);
});

And now you’re done! You can use your imported key in WebCrypto API.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents