4

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')
}
Swapnil Soni
  • 965
  • 1
  • 10
  • 26

2 Answers2

4

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');
Bola Gadalla
  • 370
  • 3
  • 14
3

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')
}
Swapnil Soni
  • 965
  • 1
  • 10
  • 26
  • I'm using [crypto-browserify](https://github.com/crypto-browserify/crypto-browserify) to encrypt on the frontend. When I decrypt on the backend I get ```error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error``` It seems like neither `pkcs1` nor `pkcs1_oaep` padding works for `crypto-browserify`. Do you have any suggestions for what to try next? – Chris Krogh Apr 09 '21 at 03:44