如何匹配 C# 和 JS CryptoJS 生成的 Key & IV

How to match Key & IV generated by C# and JS CryptoJS

我需要帮助找到一种方法来匹配 C# 和 JS 中的 IV 和 KEY,

使用简单的 C# 代码:

Rijndael rijndael = Rijndael.Create();
byte[] saltArray = Encoding.ASCII.GetBytes("20190925");
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes("password", saltArray, 1000);
rijndael.Key = pdb.GetBytes(32);
rijndael.IV = pdb.GetBytes(16);
Console.WriteLine(BitConverter.ToString(rijndael.Key).Replace("-","").ToLower());
//Output rijndael.Key = c1b34ea814586db4a22dad37e11c7256322ab0eee3a14ed1898f93d7a264242f
Console.WriteLine(BitConverter.ToString(rijndael.IV).Replace("-","").ToLower());
//Output rijndael.IV = 063ead20a9d5f35ab83e1156ebe7c099

使用 CryptoJS 我可以获得与 C# 相同的 KEY 但是使用 IV 我不明白为什么值不匹配

CryptoJS 代码:

let key = CryptoJS.PBKDF2('password', '20190925', {keySize:256/32, iterations:1000})
console.log('key', key.toString(CryptoJS.enc.Hex))
//Output key =  'key', 'c1b34ea814586db4a22dad37e11c7256322ab0eee3a14ed1898f93d7a264242f'
let iv = CryptoJS.PBKDF2('password', '20190925', {keySize:128/32, iterations:1000})
console.log('iv', iv.toString(CryptoJS.enc.Hex))
//Output iv =  'iv', 'c1b34ea814586db4a22dad37e11c7256'

我只是觉得如果 rijndael.IV = pdb.GetBytes(16); 只会得到 rijndael.Key = pdb.GetBytes(32); 十六进制的一半,但值完全不同

有没有办法使用 CryptoJS 匹配 C# 的 IV?

PBKDF2 的执行长度必须等于密钥长度和 IV 长度之和。结果分为两部分。第一部分对应key,第二部分对应IV:

let keyLen = 256/32
let ivLen = 128/32
let keyiv = CryptoJS.PBKDF2('password', '20190925', {keySize:keyLen + ivLen, iterations:1000})
let key = CryptoJS.lib.WordArray.create(keyiv.words.slice(0, keyLen));
let iv = CryptoJS.lib.WordArray.create(keyiv.words.slice(keyLen, keyLen + ivLen));
console.log('keyiv:', keyiv.toString())
console.log('key  :', key.toString())
console.log('iv   :', iv.toString())

这导致:

keyiv: c1b34ea814586db4a22dad37e11c7256322ab0eee3a14ed1898f93d7a264242f063ead20a9d5f35ab83e1156ebe7c099
key  : c1b34ea814586db4a22dad37e11c7256322ab0eee3a14ed1898f93d7a264242f
iv   : 063ead20a9d5f35ab83e1156ebe7c099

这与 C# 代码的结果匹配。