以下代码有效
var crypto = require('crypto');
var cipher = crypto.createCipher('aes-128-cbc','abcdefghijklmnop')
var http = require('http')
var userStr = 'a134aad';
var crypted = cipher.update(userStr, 'utf8', 'hex');
crypted += cipher.final('hex');
console.log(crypted);
但当放入服务器回调时,它不工作,并在请求到达时抛出以下错误,节点被压碎:
http.createServer(function(req, res){
var userStr = 'a134aad';
var crypted = cipher.update(userStr, 'utf8', 'hex');
crypted += cipher.final('hex');
console.log(crypted);
res.end('hello');
}).listen(9888)
---------------------------------
7364aee753f0568f7e5171add6868b75
crypto.js:170
var ret = this._handle.update(data, inputEncoding);
^
Error: Trying to add data in unsupported state
at Cipher.update (crypto.js:170:26)
at Server.<anonymous> (C:\Users\58\Desktop\sha256.js:12:26)
at emitTwo (events.js:126:13)
at Server.emit (events.js:214:7)
at parserOnIncoming (_http_server.js:602:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:117:23)
3条答案
按热度按时间3b6akqbq1#
原来
var cipher = crypto.createCipher('aes-128-cbc','abcdefghijklmnop')
不应该被重用。我把它也放进了服务器回调中,问题就解决了。
bqf10yzr2#
"看看这个"
这主要是因为每次运行加密或解密时,我们都要重复
crypto.createCipher('aes192', secrateKey);
和crypto.createDecipher('aes192', secrateKey);
希望这有帮助!
ha5z0ras3#
你需要创建密码之前使用它.像:
key
=可以是任何随机字符串。(我更喜欢使用32位长,因为您可能会得到一个错误,不确切的32位长的密钥)iv
=初始化向量。密钥和IV都需要在UTF-8中。
检验文件:https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options
最后的代码是这样的:
**另外,如果您发现任何错误,请随时纠正我!