C#对称加密(AES加密)每次生成的密文结果不同思路代码分享
思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | public static string Encrypt( string plainText, string AESKey) { RijndaelManaged rijndaelCipher = new RijndaelManaged(); byte [] inputByteArray = Encoding.UTF8.GetBytes(plainText); //得到需要加密的字节数组 rijndaelCipher.Key = Convert.FromBase64String(AESKey); //加解密双方约定好密钥:AESKey rijndaelCipher.GenerateIV(); byte [] keyIv = rijndaelCipher.IV; byte [] cipherBytes = null ; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cipherBytes = ms.ToArray(); //得到加密后的字节数组 cs.Close(); ms.Close(); } } var allEncrypt = new byte [keyIv.Length + cipherBytes.Length]; Buffer.BlockCopy(keyIv, 0, allEncrypt, 0, keyIv.Length); Buffer.BlockCopy(cipherBytes, 0, allEncrypt, keyIv.Length * sizeof ( byte ), cipherBytes.Length); return Convert.ToBase64String(allEncrypt); } public static string Decrypt( string showText, string AESKey) { string result = string .Empty; try { byte [] cipherText = Convert.FromBase64String(showText); int length = cipherText.Length; SymmetricAlgorithm rijndaelCipher = Rijndael.Create(); rijndaelCipher.Key = Convert.FromBase64String(AESKey); //加解密双方约定好的密钥 byte [] iv = new byte [16]; Buffer.BlockCopy(cipherText, 0, iv, 0, 16); rijndaelCipher.IV = iv; byte [] decryptBytes = new byte [length - 16]; byte [] passwdText = new byte [length - 16]; Buffer.BlockCopy(cipherText, 16, passwdText, 0, length - 16); using (MemoryStream ms = new MemoryStream(passwdText)) { using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateDecryptor(), CryptoStreamMode.Read)) { cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); } } result = Encoding.UTF8.GetString(decryptBytes).Replace( "\0" , "" ); ///将字符串后尾的'\0'去掉 } catch { } return result; } |
调用:
1 2 3 | string jiaMi = MyAESTools.Encrypt(textBox1.Text, "abcdefgh12345678abcdefgh12345678" ); string jieMi = MyAESTools.Decrypt(textBox3.Text, "abcdefgh12345678abcdefgh12345678" ); |
关注下面二维码,订阅更多精彩内容。

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 易语言 —— 开山篇
· 实操Deepseek接入个人知识库
· Trae初体验