Nodejs decrypt using crypto error wrong final block length

后端 未结 2 1199
有刺的猬
有刺的猬 2020-12-04 03:15

I use this code to crypt/decrypt string value

var crypto = require(\'crypto\');

function encrypt(text){
    var cipher = crypto.createCipher(\'aes-256-cbc\'         


        
相关标签:
2条回答
  • 2020-12-04 03:38

    The output of AES-CBC (without ciphertext stealing) is always a multiple of 16 bytes (32 hex characters). As you do not provide hexadecimal characters at all ("test") and since the string is not a multiple of 32 hexadecimal characters you will always see an error.

    So this:

    000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
    

    would for instance be valid.

    So you need to check that what you get is containing the right characters and is of the right length. To make sure that you don't get any padding or content related errors you will need to put a (hexadecimal encoded) HMAC value calculated over the ciphertext at the end. Then first check encoding, length and then the HMAC. If the HMAC is correct you can be assured that the plaintext won't contain any invalid information after decryption.

    0 讨论(0)
  • 2020-12-04 03:44

    I also faced the same issue. I had to go through all the comments to check for answer and @Alexey Ten's comment helped me. So in order to make @Alexey Ten's answer more visible below are the changes.

    var crypto = require('crypto');
    
    function encrypt(text){
      try{
        var cipher = crypto.createCipher('aes-256-cbc','secret key');
        var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex');
        return encrypted;
        } catch(exception) {
          throw exception;
        }
    }
    
    function decrypt(text){
    try{
        var decipher = crypto.createDecipher('aes-256-cbc','secret key');
        var decrypted = decipher.update(text.toString(),'hex','utf8') + decipher.final('utf8');
        return decrypted ;
      } catch(exception) {
         throw exception;
       }
    }
    
    0 讨论(0)
提交回复
热议问题