JavaScript Web Cryptography API Converting PEM key pair to CryptoKey

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


So, have you ever wondered how to use your PEM RSA key pair that was generated by OpenSSL in Web Cryptography API? If the answers is yes. Great! You are going to find out.

NOTE: This process can also be used for public key, you only need to change prefix and suffix to:

-----END PUBLIC KEY-----

This example assumes that you have your RSA key pair generated in PEM.

function removeLines(str) {
    return str.replace("\n", "");

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

    return byteArray;

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

    return base64ToArrayBuffer(b64Final);

        name: "RSA-OAEP",
        hash: {name: "SHA-256"} // or SHA-512
).then(function(importedPrivateKey) {
}).catch(function(err) {

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

Got any JavaScript Question?