C# Aes加密算法
发布日期:2022-03-30 20:19:26 浏览次数:35 分类:博客文章

本文共 2530 字,大约阅读时间需要 8 分钟。

1         ///  2         /// AES加密 对应java中的 aes/cbc/pkcs5padding 模式的算法 3         ///  4         /// 待加密的字符串 5         /// 密钥 6         /// 
7 public static string AesEncrypt(string s, string sKey) 8 { 9 AesCryptoServiceProvider provider = new AesCryptoServiceProvider();10 if (sKey == null)11 {12 throw new Exception("Key为空null");13 }14 // 判断Key是否为16位15 if (sKey.Length != 16)16 {17 throw new Exception("Key长度不是16位");18 }19 byte[] bytes = Encoding.UTF8.GetBytes(s);20 provider.Key = Encoding.UTF8.GetBytes(sKey);21 provider.IV = Encoding.UTF8.GetBytes("0102030405060708");22 MemoryStream stream = new MemoryStream();23 CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);24 stream2.Write(bytes, 0, bytes.Length);25 stream2.FlushFinalBlock();26 StringBuilder builder = new StringBuilder();27 foreach (byte num in stream.ToArray())28 {29 builder.AppendFormat("{0:X2}", num);30 }31 builder.ToString();32 stream2.Close();33 stream.Close();34 return builder.ToString();35 }36 37 /// 38 /// AES解密 对应java中的 aes/cbc/pkcs5padding 模式的算法39 /// 40 /// 待解密的字符串41 /// 密钥42 ///
43 public static string AesDecrypt(string s, string sKey)44 {45 AesCryptoServiceProvider provider = new AesCryptoServiceProvider();46 byte[] buffer = new byte[s.Length / 2];47 for (int i = 0; i < (s.Length / 2); i++)48 {49 int num2 = Convert.ToInt32(s.Substring(i * 2, 2), 0x10);50 buffer[i] = (byte)num2;51 }52 provider.Key = Encoding.UTF8.GetBytes(sKey);53 provider.IV = Encoding.UTF8.GetBytes("0102030405060708");54 MemoryStream stream = new MemoryStream();55 CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);56 stream2.Write(buffer, 0, buffer.Length);57 stream2.FlushFinalBlock();58 StringBuilder builder = new StringBuilder();59 stream2.Close();60 stream.Close();61 return Encoding.Default.GetString(stream.ToArray());62 }

 

转载地址:https://www.cnblogs.com/acool12748/p/4845787.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:UVAOJ 10061(未完结。续待)
下一篇:UVAOJ 10110 基础题 灯光 数论

发表评论

最新留言

不错!
[***.144.177.141]2024年02月18日 20时15分42秒