/// <summary> /// AesCng 加密 /// 仅支持Windows平台 /// </summary> /// <param name="value">明文(待加密)</param> /// <param name="keyValue">密钥大小为 128 位、192 位和 256 位</param> /// <returns></returns> public static (string, string) AesCngEncrypt(string value, string keyValue) { if (OperatingSystem.IsWindows()) { using (AesCng aesCng = new()) { aesCng.Key = Encoding.UTF8.GetBytes(keyValue); aesCng.GenerateIV(); using (MemoryStream memoryStream = new()) { using (CryptoStream cryptoStream = new(memoryStream, aesCng.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] plainText = Encoding.UTF8.GetBytes(value); cryptoStream.Write(plainText, 0, plainText.Length); cryptoStream.FlushFinalBlock(); return (Convert.ToBase64String(memoryStream.ToArray()), Convert.ToBase64String(aesCng.IV)); } } } } else { return (string.Empty, string.Empty); } } /// <summary> /// AesCng 解密 /// 仅支持Windows平台 /// </summary> /// <param name="value">密文(待解密)</param> /// <param name="keyValue">密钥大小为 128 位、192 位和 256 位</param> /// <param name="iv">加密时的随机初始化向量 </param> /// <returns></returns> public static string AesCngDecrypt(string value, string keyValue, string iv) { if (OperatingSystem.IsWindows()) { using (AesCng aesCng = new()) { aesCng.Key = Encoding.UTF8.GetBytes(keyValue); aesCng.IV = Convert.FromBase64String(iv); using (MemoryStream memoryStream = new(Convert.FromBase64String(value))) { using (CryptoStream cryptoStream = new(memoryStream, aesCng.CreateDecryptor(), CryptoStreamMode.Read)) { using (MemoryStream plainStream = new()) { cryptoStream.CopyTo(plainStream); return Encoding.UTF8.GetString(plainStream.ToArray()); } } } } } else { return string.Empty; } }
标签:aesCng,string,Windows,AesCng,using,net7,new,memoryStream From: https://www.cnblogs.com/yt954437595/p/17231566.html