下面的代码有效
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);
但是当进入服务器回调时,它不起作用,当请求到达并且节点被压碎时,它会在err以下抛出:
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)
答案 0 :(得分:4)
结果
var cipher = crypto.createCipher('aes-128-cbc','abcdefghijklmnop')
不应重复使用。我也将其放入服务器回调中,问题已解决。
答案 1 :(得分:0)
签出
那主要是因为我们每次运行加密或解密就要重复crypto.createCipher('aes192', secrateKey);
和crypto.createDecipher('aes192', secrateKey);
let secrateKey = "secrateKey";
const crypto = require('crypto');
function encrypt(text) {
encryptalgo = crypto.createCipher('aes192', secrateKey);
let encrypted = encryptalgo.update(text, 'utf8', 'hex');
encrypted += encryptalgo.final('hex');
return encrypted;
}
function decrypt(encrypted) {
decryptalgo = crypto.createDecipher('aes192', secrateKey);
let decrypted = decryptalgo.update(encrypted, 'hex', 'utf8');
decrypted += decryptalgo.final('utf8');
return decrypted;
}
let encryptedText = encrypt("hello");
console.log(encryptedText);
let decryptedText = decrypt(encryptedText);
console.log(decryptedText);
希望这会有所帮助!
答案 2 :(得分:0)
您需要在使用之前创建密码。喜欢:
let cipher = crypto.createCipher("aes-256-cbc", key, iv);
key
= 可以是任何随机字符串。 (我更喜欢使用 32 位长,因为您可能会因不准确的 32 位长键而出错)
iv
= 初始化向量。
key 和 iv 都需要 utf-8。
结帐文档:https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options
所以,最终的代码是这样的:
http.createServer(function(req, res){
var userStr = 'a134aad';
let key = "123456781234567812345678";
let iv= crypto.randomBytes(16);
let cipher = crypto.createCipher("aes-256-cbc", key, iv);
var crypted = cipher.update(userStr, 'utf8', 'hex');
crypted += cipher.final('hex');
console.log(crypted);
res.end('hello');
}).listen(9888)
**另外,如果您发现任何错误,请随时纠正我!