我在 C# 中使用 AES 加密字符串,如下所示:
public static byte[] KeyFromString(string key, int keyBits)// keyBits is 128, 192, or 256.
{
byte[] keyBinary = Encoding.UTF8.GetBytes(key);
byte[] b = new byte[keyBits / 8];
for (int i = 0, j = 0; i < b.Length && j < keyBinary.Length; i++, j++)
{
b[i] = keyBinary[j];
}
return b;
}
public static string encrypt(string key, string input)
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] keyBytes = KeyFromString(key, 256);
byte[] encrypted = null;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.KeySize = 256;
rijAlg.Key = keyBytes;
rijAlg.IV = new byte[rijAlg.IV.Length]; //use empty IV
using(var encryptor = rijAlg.CreateEncryptor())
{
encrypted = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
}
}
var res = Convert.ToBase64String(encrypted);
return res;
}
我想在 javascript 中解密密文,我尝试使用 crypto-js :
var iv = [];
for (var i = 0 ; i < 16 ; i++) iv.push(0); //empty IV
var options = { keySize: 256 / 8, mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7 };
var decrypted = CryptoJS.AES.decrypt(cipheredtext, key, options);
var decryptedText = decrypted.toString(CryptoJS.enc.Utf8);
我得到的解密文本是空的。我在编码、密钥大小等方面尝试了多项更改
如果需要,我可以使用另一个 javascript 库