使用非标准密钥长度调用CryptoJS.AES.encrypt/decrypt时,如何处理AES密钥

How is an AES key processed when calling CryptoJS.AES.encrypt/decrypt with a non-standard key length?

本文关键字:AES 何处理 密钥 处理 decrypt 密钥长度 非标准 调用 CryptoJS encrypt      更新时间:2023-09-26

我目前在解密C#中使用长度不是128、192或256位的密钥加密的项目时遇到问题。CryptoJS允许在加密/解密过程中使用"奇数"长度的密钥,但C#中的对称算法类(如RijndaelManaged)不允许这样做。

Javascript

var key =  CryptoJS.enc.Utf8.parse("This key is 160 bits"); // Not 128, 192, or 256 bits, but is allowed
var iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f");
var result = CryptoJS.AES.encrypt("Encrypt Me!", key, { iv: iv });
// result.ciphertext = 2839aff89d889dd29480b038679fbd6e
// or result.ciphertext.toString(CryptoJS.enc.Base64) = KDmv+J2IndKUgLA4Z5+9bg==

C#

byte[] key = Encoding.UTF8.GetBytes("This key is 160 bits");
byte[] iv = { 0x10, 0x11, 0x12, 0x13,
              0x14, 0x15, 0x16, 0x17,
              0x18, 0x19, 0x1a, 0x1b,
              0x1c, 0x1d, 0x1e, 0x1f };
byte[] encryptMe = Encoding.UTF8.GetBytes("Encrypt Me!");
using (RijndaelManaged rm = new RijndaelManaged())
{
    rm.IV = iv;
    rm.Key = key; //This is not allowed due to the key size being 160 bits. Exception thrown here.
    using (ICryptoTransform ict = rm.CreateEncryptor())
    {
        byte[] encrypted = ict.TransformFinalBlock(encryptMe, 0, encryptMe.Length);
    }
}

我的问题是,javascript代码中的密钥究竟发生了什么,才能用于加密/解密?衬料截断?CryptoJS中的AES实现是否已调整为使用"奇数"密钥长度?

我尝试过通过截断或填充(开头和结尾)字节数组来调整C#代码的键,但没有成功。我对javascript语法不是很熟悉,在查看CryptoJS源代码时,对发生的事情了解不多。

我快速查看了CryptoJS源代码,它似乎在默默地做一些非标准的事情。如果这是真的,就没有办法复制它使用标准AES所做的事情。

但是,为了确保没有密钥派生之类的东西,请尝试执行alert(result.key);,看看它是否与您的输入相同。