nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.44k stars 276 forks source link

crypto.privateDecrypt throwing Error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error #4419

Closed packcode closed 1 week ago

packcode commented 3 weeks ago

Node.js Version

v16.17.0

NPM Version

v8.15.0

Operating System

Windows 10

Subsystem

crypto

Description

A client of us is sending encrypted response using javax.crypto.Cipher; with padding scheme RSA/ECB/PKCS1Padding and a public key when I an trying to decrypt the response using crypto.privateDecrypt using a private key it is throwing error

crypto.privateDecrypt throwing Error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error

Minimal Reproduction

Java Code Snippet to encrypt the response:

private String getRequestkey(String randomNUmber) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, IOException {
Cipher ci = Cipher.getInstance("RSA/ECB/PKCS1Padding");

X509Certificate cert = getCertificate(PUBLIC_CERTIFICATE);
ci.init(Cipher.ENCRYPT_MODE, cert.getPublicKey());

byte[] input = randomNUmber.getBytes("UTF-8");
String key = Base64.getEncoder().encodeToString(ci.doFinal(input));

logger.info("encrytpedKey " + key);
return key;
}

Crypto decryption:

function rsaDecryptNew(privateKey, encryptedData) {
  const decryptedData = crypto.privateDecrypt(
    {
      key: buildPrivateKey(privateKey),
      padding: crypto.constants.RSA_PKCS1_PADDING,
    },
    Buffer.from(encryptedData, 'base64'),
  );

  return decryptedData.toString('utf8');
}

function buildPrivateKey(privateKey) {
  const privateKeyBuffer = Buffer.from(privateKey, 'base64');
  return crypto.createPrivateKey({ key: privateKeyBuffer, format: 'der', type: 'pkcs8' });
}

Output

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

Error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error

Before You Submit

RedYetiDev commented 3 weeks ago

Hi! The version of node you are using is EoL, can you reproduce in a supported Node.js version?

RedYetiDev commented 2 weeks ago

@preveen-stack FWIW it seems like this isn't specific to windows, but instead the way crypto is used

packcode commented 1 week ago

@RedYetiDev At the business partner's end, there was a problem with the key configuration. The decryption process operates flawlessly once the correct public and private keys have been updated.

RedYetiDev commented 1 week ago

I'm glad to fixed your problem!