我正在尝试使用 C# 加密字符串并使用 Angular crypto-js 库对其进行解密,但它给了我不同的输出。我尝试了不同的 c# aes 加密实现,但 crypto-js 库无法解密 c# 中的加密数据。感谢您的任何帮助。这是我的代码程序.cs static void Main() { var r = EncryptString("exampleString", "examplePassword"); Console.Write(r); } public static string EncryptString(string plainText, string passPhrase) { if (string.IsNullOrEmpty(plainText)) { return ""; } // generate salt byte[] key, iv; var salt = new byte[8]; var rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(salt); DeriveKeyAndIv(passPhrase, salt, out key, out iv); // encrypt bytes var encryptedBytes = EncryptStringToBytesAes(plainText, key, iv); // add salt as first 8 bytes var encryptedBytesWithSalt = new byte[salt.Length + encryptedBytes.Length + 8]; Buffer.BlockCopy(Encoding.ASCII.GetBytes("Salted__"), 0, encryptedBytesWithSalt, 0, 8); Buffer.BlockCopy(salt, 0, encryptedBytesWithSalt, 8, salt.Length); Buffer.BlockCopy(encryptedBytes, 0, encryptedBytesWithSalt, salt.Length + 8, encryptedBytes.Length); // base64 encode return Convert.ToBase64String(encryptedBytesWithSalt); } private static void DeriveKeyAndIv(string passPhrase, byte[] salt, out byte[] key, out byte[] iv) { // generate key and iv var concatenatedHashes = new List<byte>(48); var password = Encoding.UTF8.GetBytes(passPhrase); var currentHash = new byte[0]; var md5 = MD5.Create(); bool enoughBytesForKey = false; // See http://www.openssl.org/docs/crypto/EVP_BytesToKey.html#KEY_DERIVATION_ALGORITHM while (!enoughBytesForKey)
1 回答
互换的青春
TA贡献1797条经验 获得超6个赞
示例代码试图解密原始的未加密字符串,这看起来可能是在尝试简化发布问题的示例代码时造成的错误?无论哪种方式,所需的步骤都不太困难,但需要替换 toString() 调用。
var data = "U2FsdGVkX1/Zvh/5BnLfUgfbg5ROSD7Aohumr9asPM8="; // Output from C#
let r2 = CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(data, 'examplePassword'));
console.log(r2);
添加回答
举报
0/150
提交
取消