C#与Java AES 加密解密
参考文档:https://www.cnblogs.com/xbzhu/p/7064642.html
前几天对接Java接口,需要C#加密参数,Java解密。奈何网上找了一堆大同小异的加解密方法都跟Jaca加密的密文不一致,Java接口也无法解密,直到看见上面链接的第二种方法。能够正常的解密Java加密的密文,说明此方法有效,但这里只有解密,我需要的是加密方法(伸手党做习惯了),没办法读读代码看看是怎么解密的,巧了看到了 CreateDecryptor 改一下 试一下解密 跟Java完全一致 成功!感谢博主!
这是参考文档的博主写的Demo:https://github.com/zhu-xb/AES-Cryptography
/// <summary> /// AES解密 /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static string AESDecrypt(string content, string key) { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(Encoding.ASCII.GetBytes(key)); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()) { aesProvider.Key = enCodeFormat; aesProvider.Mode = CipherMode.ECB; aesProvider.Padding = PaddingMode.PKCS7; using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor()) { byte[] inputBuffers = Convert.FromBase64String(content); byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length); aesProvider.Clear(); return Encoding.UTF8.GetString(results); } } }
/// <summary> /// AES加密 /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static string AESEncrypt(string content, string key) { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(Encoding.ASCII.GetBytes(key)); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()) { aesProvider.Key = enCodeFormat; aesProvider.Mode = CipherMode.ECB; aesProvider.Padding = PaddingMode.PKCS7; using (ICryptoTransform cryptoTransform = aesProvider.CreateEncryptor()) { byte[] inputBuffers = Encoding.UTF8.GetBytes(content); byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length); aesProvider.Clear(); return Convert.ToBase64String(results); } } }
再次感谢博主 朱小波 https://www.cnblogs.com/xbzhu/