C#与Java加密解密互通之AES算法
前不久做一个项目接口对接,C#的程序调用Java程序的Api接口,而这个Api接口为了安全性,所有参数必须统一采用AES和RSA加密算法进行加密,返回的结果也是经过Java的AES和RSA加密。本来以为C#和Java常用的AES加密解密都是互通的,没想到完全不是那么一回事。网上也查了不少方案,靠谱的几乎没有,几经摸索,终于找到了AES算法互通的方案。下面直接上代码。
C# AES加密解密程序。
using System; using System.Security.Cryptography; using System.Text; namespace AESUtils { public class AESUtils { /// <summary>AES加密</summary> /// <param name="text">明文</param> /// <param name="key">密钥,长度为16的字符串</param> /// <returns>密文</returns> public static string EncodeAES(string text, string key) { RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; rijndaelCipher.KeySize = 128; rijndaelCipher.BlockSize = 128; byte[] pwdBytes = Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[16]; int len = pwdBytes.Length; if (len > keyBytes.Length) len = keyBytes.Length; Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; rijndaelCipher.IV = keyBytes; ICryptoTransform transform = rijndaelCipher.CreateEncryptor(); byte[] plainText = Encoding.UTF8.GetBytes(text); byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length); return Convert.ToBase64String(cipherBytes); } /// <summary>AES解密</summary> /// <param name="text">密文</param> /// <param name="key">密钥,长度为16的字符串</param> /// <returns>明文</returns> public static string DecodeAES(string text, string key) { RijndaelManaged rijndaelCipher = new RijndaelManaged(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.PKCS7; rijndaelCipher.KeySize = 128; rijndaelCipher.BlockSize = 128; byte[] encryptedData = Convert.FromBase64String(text); byte[] pwdBytes = Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[16]; int len = pwdBytes.Length; if (len > keyBytes.Length) len = keyBytes.Length; Array.Copy(pwdBytes, keyBytes, len); rijndaelCipher.Key = keyBytes; rijndaelCipher.IV = keyBytes; ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(plainText); } } }
Java核心加密解密程序。
import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESUtils { /** * AES算法加密明文 * @param data 明文 * @param key 密钥,长度16 * @param iv 偏移量,长度16 * @return 密文 */ public static String encryptAES(String data,String key,String iv) throws Exception { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //or NoPadding int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return Base64Helper.encode(encrypted).trim(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * AES算法解密密文 * @param data 密文 * @param key 密钥,长度16 * @param iv 偏移量,长度16 * @return 明文 */ public static String decryptAES(String data,String key,String iv) throws Exception { try { byte[] encrypted1 = Base64Helper.decode(data); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //or NoPadding SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString.trim(); } catch (Exception e) { e.printStackTrace(); return null; } } }
Java的Base64的帮助类。
import org.apache.commons.codec.binary.Base64; public class Base64Helper { /** * 编码 * @param byteArray * @return */ public static String encode(byte[] byteArray) { return new String(new Base64().encode(byteArray)); } /** * 解码 * @param base64EncodedString * @return */ public static byte[] decode(String base64EncodedString) { return new Base64().decode(base64EncodedString); } }
亲测可用。C#加密的的密文,Java里面用同样的密钥可以解密;而Java加密的密文,在C#里面用同样的密钥也可以成功解密。
C#测试结果:
Java的测试结果:
谁有更好的建议敬请留言。