0

I want to export my RSA key pair to pem, that I've created with windows.crypto.subtle API, but with AES-128-CFB encryption. I know how to do this with Node.js with the crypto package, I want to do it on the client side. How can I do that?

I would like to achive something similar to this:

const { generateKeyPair } = require('crypto');

let RSAKeyGenerator= 
{
    async generate(password)
    {
        return new Promise(function (resolve, reject) {
            generateKeyPair('rsa', {
                modulusLength: 2048,
                publicExponent: 0x10001,
                publicKeyEncoding: {
                type: 'pkcs1',
                format: 'pem'
                },
                privateKeyEncoding: {
                type: 'pkcs8',
                format: 'pem',
                cipher: 'AES-128-CFB',
                passphrase: password
                }
            }, 
            function (error, publicKey, privateKey)
            {
                if(!error)
                {
                    resolve({
                        publicKey: publicKey,
                        privateKey: privateKey
                    });
                }
                console.error(error);
                reject({
                    error: error,
                    publicKey: null,
                    privateKey: null
                });  
            });
    });
    }
}
Zsolt
  • 304
  • 2
  • 8
  • 1
    Questions: 1. Why do you want to do it client-side? 2. Are you expecting a private key to remain secret and hidden in a browser? What use case are you trying to satisfy? – Jeremy Thille Dec 21 '21 at 12:42
  • Because I would like to encrypt it with the password of the user, and that is also going to be hashed on the client side. – Zsolt Dec 21 '21 at 12:49
  • What about the second question? Also, why not do it server-side with the client password? – Jeremy Thille Dec 21 '21 at 13:12
  • Because that's what my task requires, I'm only responsible for the front-end. – Zsolt Dec 21 '21 at 13:45
  • Ok, but second question again, since it remains unanswered: are you expecting a private key to remain secret and hidden in a browser? Because if you do, I have some bad news for you – Jeremy Thille Dec 21 '21 at 13:48
  • https://stackoverflow.com/questions/68093193/using-nodejs-crypto-module-in-browser-with-webpack – Jeremy Thille Dec 21 '21 at 13:51
  • 1
    WebCrypto provides [`exportKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey) for the key export. However, only DER is supported, not PEM. The associated formats are PKCS#8 and X.509/SPKI. The conversion to PEM must be done by yourself (which is fairly simple: Base64 encoding with line breaks plus header and footer). – Topaco Dec 21 '21 at 15:32

0 Answers0