Getting error "wrong final block length" when decrypting AES256 cipher Getting error "wrong final block length" when decrypting AES256 cipher mongoose mongoose

Getting error "wrong final block length" when decrypting AES256 cipher


This question is two years old at the time of this writing, but it has quite a few views, so I hope this answer will still prove useful to someone who might come across it.

The problem here is that encryptText works fine, but it's not returning a string. It's returning a Buffer. decryptText is expecting a string, not a Buffer, so it tries to read it as though it were a Buffer and you get the error that you received.

This is a simple fix. We just need to serialise the Buffer to a string when we encrypt text, and deserialise the encrypted string we receive when we decrypt text.

In this example, I use base64 encoding because it is fairly compact when representing binary data.

var config = {  cryptkey: crypto.createHash('sha256').update('Nixnogen').digest(),  iv: 'a2xhcgAAAAAAAAAA'}function encryptText (text) {  console.log(config.cryptkey)  var cipher = crypto.createCipheriv('aes-256-cbc', config.cryptkey, config.iv)  return Buffer.concat([    cipher.update(text),    cipher.final()  ]).toString('base64') // Output base64 string}function decryptText (text) {  console.log(config.cryptkey)  if (text === null || typeof text === 'undefined' || text === '') {    return text  }  var decipher = crypto.createDecipheriv('aes-256-cbc', config.cryptkey, config.iv)  return Buffer.concat([    decipher.update(text, 'base64'), // Expect `text` to be a base64 string    decipher.final()  ]).toString()}var encrypted = encryptText('text') // 8xXuS7jLG6crqJFHHB5J5A==var decrypted = decryptText(encrypted) // text