參考文檔:https://www.cnblogs.com/xbzhu/p/7064642.html 這是參考文檔的博主寫的Demo:https://github.com/zhu-xb/AES-Cryptography 再次感謝博主 朱小波 https://www.cnblogs.com/xbzhu/ ...
參考文檔: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/