Nodejs decrypt using crypto error wrong final block length

后端 未结 2 1227
有刺的猬
有刺的猬 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.

提交回复
热议问题