Nodejs crypto aes-256-cbc: The argument 'encoding' is invalid for data of length 383. Received 'hex'

81 views Asked by At

I am encrypting JWT tokens using crypto with Node.js. After a user logs in, I provide the encrypted tokens to the client. Then, whenever the client sends these encrypted tokens back to me along with a request, I decrypt them and continue with the process.

However, sometimes I encounter this error while decrypting the encrypted tokens:

enter image description here

The functions I use to encrypt and decrypt tokens are provided below. The error I mentioned above occurs in the decryptData function, which I handle in the catch block.

Here is the code:

const crypto = require("crypto");

const key = crypto
   .createHash('sha512')
   .update(process.env.AES_SECRET_KEY)
   .digest('hex')
   .substring(0, 32)

const encryptionIV = crypto
   .createHash('sha512')
   .update(process.env.AES_SECRET_IV)
   .digest('hex')
   .substring(0, 16)

const method = 'aes-256-cbc'

// Encrypt data
exports.encryptData = (data) => {
   try {
      const cipher = crypto.createCipheriv(method, key, encryptionIV)
      return Buffer.from(
         cipher.update(data, 'utf8', 'hex') + cipher.final('hex')
      ).toString('base64') 
   } catch (error) {
    return undefined
   }
}

// Decrypt data
exports.decryptData = (encryptedData) => {
   try {
      const buff = Buffer.from(encryptedData, 'base64')
      const decipher = crypto.createDecipheriv(method, key, encryptionIV)
      return (
         decipher.update(buff.toString('utf8'), 'hex', 'utf8') +
         decipher.final('utf8')
      ) 
   } catch (error) {
      return undefined
   }
}
0

There are 0 answers