对接接口中遇到一个棘手的问题:甲方使用java开发,通过AES加密数据,我方使用C#开发,Java的代码和C#的代码无法互通。
1 /// <summary> 2 /// AES加密(128位,密码模式ECB,填充类型PKCS5Padding或者PKCS7Padding。注:ECB模式不需要初始化向量iv。) 3 /// </summary> 4 /// <param name="str"></param> 5 /// <param name="key"></param> 6 /// <returns></returns> 7 public static string AES_Encrypt(string str, string key) 8 { 9 if (string.IsNullOrEmpty(str)) return null; 10 Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); 11 12 RijndaelManaged rm = new RijndaelManaged 13 { 14 Key = Convert.FromBase64String(key), 15 Mode = CipherMode.ECB, 16 Padding = PaddingMode.PKCS7 17 }; 18 19 ICryptoTransform cTransform = rm.CreateEncryptor(); 20 Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 21 StringBuilder ret = new StringBuilder(); 22 foreach (byte b in resultArray.ToArray()) 23 { 24 ret.AppendFormat("{0:X2}", b); 25 } 26 return Convert.ToBase64String(resultArray, 0, resultArray.Length); 27 }
1 /// <summary> 2 /// AES解密(128位,密码模式ECB,填充类型PKCS5Padding或者PKCS7Padding。注:ECB模式不需要初始化向量iv。) 3 /// </summary> 4 /// <param name="toDecrypt"></param> 5 /// <param name="key"></param> 6 /// <returns></returns> 7 public static string AES_Decrypt(string toDecrypt, string key) 8 { 9 byte[] keyArray = Convert.FromBase64String(key); //将TestGenAESByteKey类输出的字符串转为byte数组 10 byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); 11 RijndaelManaged rDel = new RijndaelManaged(); 12 rDel.Key = keyArray; 13 rDel.Mode = CipherMode.ECB; //必须设置为ECB 14 rDel.Padding = PaddingMode.PKCS7; //必须设置为PKCS7 15 ICryptoTransform cTransform = rDel.CreateDecryptor(); 16 byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); 17 return UTF8Encoding.UTF8.GetString(resultArray); 18 19 }