Getting error “wrong final block length” when decrypting AES256 cipher

后端 未结 1 422
悲哀的现实
悲哀的现实 2020-12-07 04:36

I\'m facing exactly the same problem mentioned in this thread while encrypting and decrypting using AES.

crypto.js:202
var ret = this._handle.fi

相关标签:
1条回答
  • 2020-12-07 05:26

    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
    
    0 讨论(0)
提交回复
热议问题