Nodejs使用加密错误解密最终块长度错误 [英] Nodejs decrypt using crypto error wrong final block length

查看:16
本文介绍了Nodejs使用加密错误解密最终块长度错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码加密/解密字符串值

I use this code to crypt/decrypt string value

var crypto = require('crypto');

function encrypt(text){
    var cipher = crypto.createCipher('aes-256-cbc','secret key');
    var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex');
    return encrypted;
}

function decrypt(text){
    var decipher = crypto.createDecipher('aes-256-cbc','secret key');
    var decrypted = decipher.update(text.toString(),'hex','utf8') + decipher.final('utf8');
    return decrypted ;
}

module.exports.encrypt = encrypt;
module.exports.decrypt = decrypt;

当我尝试解密未加密的东西时,例如解密('test'),它会抛出以下错误:

When i try to decrypt something that isn't crypted for example decrypt('test') it throw me the following error :

crypto.js:292
  var ret = this._binding.final();
                          ^
TypeError: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
    at Decipher.Cipher.final (crypto.js:292:27)

我也尝试使用缓冲区但没有成功,但在 Internet 上找不到任何解决方案.

I tryed also to use buffers without sucess and couldn't find any solution over Internet.

真正的问题是我用它来解密 cookie 值.如果黑客创建了一个值为test"的虚假 cookie,它将使我的程序崩溃.

The real problem is I use this to decrypt cookie value. If a hacker creates a fake cookie with the value "test" it will crash my program.

推荐答案

AES-CBC 的输出(没有密文窃取)始终是 16 字节(32 个十六进制字符)的倍数.由于您根本不提供十六进制字符(test"),并且由于字符串不是 32 个十六进制字符的倍数,因此您将始终看到错误.

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.

所以这个:

000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F

例如是有效的.

因此,您需要检查您得到的内容是否包含正确的字符并且长度是否正确.为了确保您没有收到任何填充或内容相关的错误,您需要在最后放置一个通过密文计算的(十六进制编码的)HMAC 值.然后首先检查编码、长度,然后检查 HMAC.如果 HMAC 是正确的,则可以确保明文在解密后不会包含任何无效信息.

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.

这篇关于Nodejs使用加密错误解密最终块长度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆