NodeJS 尝试在Cipher.update中添加处于不支持状态的数据

8wtpewkr  于 2023-03-08  发布在  Node.js
关注(0)|答案(3)|浏览(112)

以下代码有效

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)
3b6akqbq

3b6akqbq1#

原来
var cipher = crypto.createCipher('aes-128-cbc','abcdefghijklmnop')
不应该被重用。我把它也放进了服务器回调中,问题就解决了。

bqf10yzr

bqf10yzr2#

"看看这个"
这主要是因为每次运行加密或解密时,我们都要重复crypto.createCipher('aes192', secrateKey);crypto.createDecipher('aes192', secrateKey);

let secrateKey = "secrateKey";
const crypto = require('crypto');

function encrypt(text) {
    const encryptalgo = crypto.createCipher('aes192', secrateKey);
    let encrypted = encryptalgo.update(text, 'utf8', 'hex');
    encrypted += encryptalgo.final('hex');
    return encrypted;
}

function decrypt(encrypted) {
    const 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);

希望这有帮助!

ha5z0ras

ha5z0ras3#

你需要创建密码之前使用它.像:

let cipher = crypto.createCipher("aes-256-cbc", key, iv);

key =可以是任何随机字符串。(我更喜欢使用32位长,因为您可能会得到一个错误,不确切的32位长的密钥)
iv =初始化向量。
密钥和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)

**另外,如果您发现任何错误,请随时纠正我!

相关问题