Reputation: 69
I am not getting the same results when switching from C# to JS:
Converting from this:
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();
To this:
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);
}
}
But it's not working for some reason
I tried Buffer.from(pass, 'utf8') and so one but I am never getting the same result.
I know I have something wrong but I have no idea how pbkdf2 works
Upvotes: 2
Views: 1039
Reputation: 69
For anyone in the same problem as I am this is the equivalent code
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);
Upvotes: 2