问题描述
我在Node的加密库中遇到了奇怪的问题。我写了这个简单的AES测试脚本:var cipher = crypto.createCipher('aes-256-cbc','InmbuvP6Z8' )
当我做console.log(dec)时,它是空的,/ pre>
var text =123 | 123123123123123;
cipher.update(text,'utf8','hex')
var crypted = cipher.final('hex')
var decipher = crypto.createDecipher('aes-256-cbc ','InmbuvP6Z8')
decipher.update(crypted,'hex','utf8')
var dec = decipher.final('utf8')
由于某些原因,如果我将测试设置为123 | 123123,它可以工作。那么为什么123 | 123123工作,但是123 | 123123123123123没有?
解决方案你需要存储返回来自cipher.update以及cipher.final,以确保你拥有一切。
cipher.update返回加密内容,可以使用新数据多次调用因为它是流:
加密。最终返回任何剩余的加密内容。
我认为您只需每次调用结果即可:
var crypto = require('crypto');
var cipher = crypto.createCipher('aes-256-cbc','InmbuvP6Z8');
var text =123 | 123123123123123;
var crypted = cipher.update(text,'utf8','hex');
crypted + = cipher.final('hex');
var decipher = crypto.createDecipher('aes-256-cbc','InmbuvP6Z8');
var dec = decipher.update(crypted,'hex','utf8');
dec + = decipher.final('utf8');
我得到'12443a347e8e5b46caba9f7afc93d71287fbf11169e8556c6bb9c51760d5c585'用于加密,'123 | 123123123123123'用于上面的节点v0 .2.5
I'm having weird issues with Node's crypto library. I wrote this simple AES testing script:
var cipher = crypto.createCipher('aes-256-cbc','InmbuvP6Z8') var text = "123|123123123123123"; cipher.update(text,'utf8','hex') var crypted = cipher.final('hex') var decipher = crypto.createDecipher('aes-256-cbc','InmbuvP6Z8') decipher.update(crypted,'hex','utf8') var dec = decipher.final('utf8')
When I do console.log(dec), it's null. For some reason if I set test to "123|123123", it works. So why does "123|123123" work but "123|123123123123123" doesn't?
解决方案You need to store the return from cipher.update as well as cipher.final to be sure you have everything.
cipher.update "returns the enciphered contents, and can be called many times with new data as it is streamed":
http://nodejs.org/docs/v0.2.5/api.html#cipher-update-247
cipher.final "returns any remaining enciphered contents".
I think you just append the results with each call like this:
var crypto = require('crypto'); var cipher = crypto.createCipher('aes-256-cbc','InmbuvP6Z8'); var text = "123|123123123123123"; var crypted = cipher.update(text,'utf8','hex'); crypted += cipher.final('hex'); var decipher = crypto.createDecipher('aes-256-cbc','InmbuvP6Z8'); var dec = decipher.update(crypted,'hex','utf8'); dec += decipher.final('utf8');
I get '12443a347e8e5b46caba9f7afc93d71287fbf11169e8556c6bb9c51760d5c585' for crypted and '123|123123123123123' for dec in the above with node v0.2.5
这篇关于Node.js和加密库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!