[Nodejs - Crypto][JSencrypt] rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error

4.1k views Asked by At

I'm using NodeJS Crypto module for encrypting and decrypting with RSA in backend and JSencrypt for frontend RSA

But issue is my backend throws this error whenever I encrypt in frontend using publickey (PS: I'm using this in NuxtJS so using import function.)

const { JSEncrypt } = await import('jsencrypt')
const rsa = new JSEncrypt({ default_key_size: 1024 })
rsa.setPublicKey(store.state.publicKey)
const xKey = rsa.encrypt(store.state.ticket)

and then whenever I try to decode using this piece of code in my backend it throws this

Error: error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error

Here is my backend code for RSA decoding using privateKey

const privateKey = fs.readFileSync('RSA_private.key', { encoding: 'utf8' })

exports.RSAdecrypt = async (data) => {
    const buffer = Buffer.from(data, "base64")
    const decrypted = crypto.privateDecrypt(privateKey, buffer)
    return decrypted.toString('utf8')
}
2

There are 2 answers

1
Swapnil Soni On BEST ANSWER

I found a solution. I saw on this post that JSencrypt uses pkcs1 padding by default. so I have changed my decryptor with pkcs1 Bydefault node crypto uses pkcs1_oaep by default.

here is code for decryptor.

exports.RSAdecrypt = async (data) => {
    const buffer = Buffer.from(data, "base64")
    const decrypted = crypto.privateDecrypt({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PADDING }, buffer)
    return decrypted.toString('utf8')
}
0
Bola Gadalla On

If people are still having errors, because I got a different error when I did the same thing as the answer here, you might want to pass the crypto constant no padding like this:

crypto.privateDecrypt(
      {
        key: this.privateKey,
        passphrase: '<passPhrase>',
        padding: crypto.constants.RSA_NO_PADDING, // <-- You might want to try this
      }, 
      Buffer.from(encryptedText, 'base64')).toString('utf8');