1 /// <summary> 2 /// AES加密 对应java中的 aes/cbc/pkcs5padding 模式的算法 3 /// </summary> 4 /// <param name="s">待加密的字符串</param> 5 /// <param name="sKey">密钥</param> 6 /// <returns></returns> 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 /// <summary> 38 /// AES解密 对应java中的 aes/cbc/pkcs5padding 模式的算法 39 /// </summary> 40 /// <param name="s">待解密的字符串</param> 41 /// <param name="sKey">密钥</param> 42 /// <returns></returns> 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 }
时间: 2024-10-12 12:28:19