从C#切换到JS时,我没有得到相同的结果。
从此转换:
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(
passPhrase,
Encoding.UTF8.GetBytes(saltValue)
);
MemoryStream ms = new MemoryStream();
Aes aes = new AesManaged();
aes.Key = pdb.GetBytes(aes.KeySize / 8);
aes.IV = pdb.GetBytes(aes.BlockSize / 8);
CryptoStream cs = new CryptoStream(ms,
aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close();
ms.Close();
aes.Clear();
return ms.ToArray();
对此:
crypto.pbkdf2(Buffer.from(pass), Buffer.from(salt, 'hex'), 1000, 256 / 8, null, function (err, key) {
console.log("Key:" + key);
crypto.pbkdf2(Buffer.from(pass), Buffer.from(salt, 'hex'), 1000, 128 / 8, null, function (err, key) {
console.log("VID:" + key);
}
}
但是由于某些原因它无法正常工作
我尝试了Buffer.from(pass,'utf8')等,但我从未得到相同的结果。
我知道我做错了什么,但我不知道pbkdf2的工作原理
答案 0 :(得分:1)
对于与我有同样问题的任何人,这是等效的代码
var pass = 'password';
var salt = 'salt';
var keyLen = keylen; // aes.KeySize / 8 where KeySize is 256
var IVLen = ivlen; // aes.BlockSize / 8 where BlockSize is 128
var nodeCrypto = crypto.pbkdf2Sync(pass, salt, 1000, keyLen + IVLen, 'sha1');
// Output same values as C# Bytes
var aesKey = [], aesIV = [];
for (var i = 0; i < nodeCrypto.length; i++) {
if (i < keyLen)
aesKey[i] = nodeCrypto[i];
else
aesIV[i - keyLen] = nodeCrypto[i];
}
console.log(aesKey);
console.log(aesIV);
// How to use it to decrypt
var r = fs.createReadStream(path);
var decrypt = crypto.createDecipheriv('aes-256-cbc', nodeCrypto.slice(0, keyLen), nodeCrypto.slice(keyLen, keyLen + IVLen));
var w = fs.createWriteStream(output);
r.pipe(decrypt).pipe(w);