Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passphrase required for encrypted key

Tags:

node.js

I use generateKeyPair to create public key and private key

 const { generateKeyPair } = crypto
generateKeyPair('rsa', {
    modulusLength: 4096,
    publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: 'top secret'
    }
}, (err, publicKey, privateKey) => {
    // Handle errors and use the generated key pair.
    if (err) throw err;
    fs.writeFileSync("key.pem", privateKey)
    fs.writeFileSync("public.pem", publicKey)
    res.json({ publicKey, privateKey })

});

and I use public key to encrypt,it works but when I use the privatekey to decrypt,it comes an error the code is

    fs.readFile("key.pem", "utf8", (err, data) => {
            const content = crypto.privateDecrypt(data, Buffer.from(c, "base64"))//c is the cipherText and the error happends here

    })



    error message is :
     return method(data, format, type, passphrase, buffer, padding, oaepHash,

TypeError: Passphrase required for encrypted key

so I don't understand what's that mean, bcuz the API is :crypto.privateDecrypt(privateKey, buffer) and when I generate it , I have passed the 'passphrase', so I have no idea about it

like image 799
homy Avatar asked May 15 '26 10:05

homy


1 Answers

I ran into a very similar issue. You have to use the function privateDecrypt in the following manner

var decrypted = crypto.privateDecrypt({
    key: privateKey.toString(),
    passphrase: 'top secret',
  }, buffer);
like image 120
kaushalop Avatar answered May 18 '26 02:05

kaushalop