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

查看:1368
本文介绍了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个十六进制字符)的倍数。由于您不提供十六进制字符(测试),并且由于字符串不是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天全站免登陆