Kunoichi Asked:2021-11-25 03:30:57 +0000 UTC2021-11-25 03:30:57 +0000 UTC 2021-11-25 03:30:57 +0000 UTC C#加密一个总是不同结果的字符串 772 必须以相同的密钥总是产生不同的结果的方式加密字符串。在 AES 算法中,您可以为此使用不同的向量,但对于解密,除了密钥之外,您还需要知道该向量。我有必要仅在密钥上接收唯一的加密消息。我可以为此使用哪些算法? c# 1 个回答 Voted Best Answer aepot 2021-11-25T04:03:27Z2021-11-25T04:03:27Z 我会做这样的事情,实际上结果是符合您条件的结果。 static void Main(string[] args) { string text = "Hello World!"; byte[] key = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray(); Console.WriteLine(Encrypt(text, key)); Console.WriteLine(Encrypt(text, key)); Console.WriteLine(Encrypt(text, key)); Console.WriteLine(Encrypt(text, key)); string base64 = Encrypt(text, key); Console.WriteLine(base64); Console.WriteLine(Decrypt(base64, key)); Console.ReadKey(); } private static string Encrypt(string text, byte[] key) { using Aes aes = Aes.Create(); aes.Key = key; using MemoryStream ms = new(); ms.Write(aes.IV); using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true)) { cs.Write(Encoding.UTF8.GetBytes(text)); } return Convert.ToBase64String(ms.ToArray()); } private static string Decrypt(string base64, byte[] key) { using MemoryStream ms = new(Convert.FromBase64String(base64)); byte[] iv = new byte[16]; ms.Read(iv); using Aes aes = Aes.Create(); aes.Key = key; aes.IV = iv; using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true); using MemoryStream output = new(); cs.CopyTo(output); return Encoding.UTF8.GetString(output.ToArray()); } 控制台输出 130gYdJGjVNVWeCp8ep8kLlyX39fg1nY4vl99wNIYIw= TstMTm9mvyjiO9nM2M8sdoYLktkpmMRolhGYGPCbwpM= HGM8CIiXaBpluZdBBggR2yXXeGpDTMkLi/OreZQWPnE= /sE0aIsc0wkcc3kP3df9TWPRBt/2/OKSd1eAORSBCOc= Kd6JMwFkMRae1sgjEks76j7+kfRR1Lb3Vz3NVj7DeRw= Hello World! 始终使用相同的密钥生成不同的输出,因为它每次都会Aes生成一个随机输出。IV
我会做这样的事情,实际上结果是符合您条件的结果。
控制台输出
始终使用相同的密钥生成不同的输出,因为它每次都会
Aes生成一个随机输出。IV