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

查看:23
本文介绍了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;

当我尝试解密未加密的内容时,例如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天全站免登陆