Narasimhan R
Narasimhan R

Reputation: 51

Exception when using privateEncrypt/privateDecrypt with certain encrypted keys

Steps:

Code:

const crypto = require("crypto");
let {privateKey, publicKey} = crypto.generateKeyPairSync("rsa", {
    modulusLength: 2048,
    publicKeyEncoding: {
        type: "spki",
        format: "pem"
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: "aes-128-ecb",
        passphrase: "abcdef"
    }
});
const encryptedString = crypto.privateEncrypt({
    key: privateKey,
    passphrase: "abcdef"
}, Buffer.from("The quick brown fox jumps over the lazy dog")).toString("base64");
const decryptedString = crypto.publicDecrypt(publicKey, Buffer.from(encryptedString, "base64")).toString();
console.log(`Encrypted: ${encryptedString}`);
console.log(`Decrypted: ${decryptedString}`);

I can successfully encryption/decryption with the specified ciphers but it shows following error

node:internal/crypto/cipher:79
    return method(data, format, type, passphrase, buffer, padding, oaepHash,
           ^

Error: error:060CC07A:digital envelope routines:EVP_CIPHER_asn1_to_param:cipher parameter error
    at Object.privateEncrypt (node:internal/crypto/cipher:79:12)
    at Object.<anonymous> (/home/pancho7532/Documents/AnotherBotXDDXD/rsaTest.js:25:32)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  opensslErrorStack: [
    'error:060CC07A:digital envelope routines:EVP_CIPHER_asn1_to_param:cipher parameter error'
  ],
  library: 'digital envelope routines',
  function: 'EVP_CIPHER_asn1_to_param',
  reason: 'cipher parameter error',
  code: 'ERR_OSSL_EVP_CIPHER_PARAMETER_ERROR'
}

Upvotes: 1

Views: 1195

Answers (1)

FireLeopard
FireLeopard

Reputation: 317

It took me a while to work this out, but seems to be an issue with the cipher property. Try using a different cipher.

I tried aes-256-ecb, aes-128-ecb and bf-ecb, none of them worked, then I tried aes-256-cbc, aes-128-cbc and bf-cbc and they all worked. I am not sure why but privateEncrypt() only seems to like all the same ciphers as generateKeyPairSync() does, specifically the "ecb" type.

With some Googling, it seems aes-128-cbc is generally considered better than aes-128-ecb, so maybe that is preferable anyway.

Upvotes: 2

Related Questions