和某上市公司对接接口,他们试用 java AES CBC PKCS5 256 加解密。网上C# 基本不合适。
注意:C# PKCS7 对应 java PKCS5
/// <summary> /// AES加密 /// </summary> /// <param name="encryptStr">明文</param> /// <param name="key">密钥</param> /// <returns></returns> protected string Encrypt(string encryptStr, string key) { var _aes = new AesCryptoServiceProvider(); _aes.BlockSize = 128; _aes.KeySize = 256; _aes.Key = Encoding.UTF8.GetBytes(key); _aes.IV = (byte[])(object)new sbyte[16];//Encoding.UTF8.GetBytes(IV); _aes.Padding = PaddingMode.PKCS7; _aes.Mode = CipherMode.CBC; var _crypto = _aes.CreateEncryptor(_aes.Key, _aes.IV); byte[] encrypted = _crypto.TransformFinalBlock(Encoding.UTF8.GetBytes(encryptStr), 0, Encoding.UTF8.GetBytes(encryptStr).Length); _crypto.Dispose(); return System.Convert.ToBase64String(encrypted); }
/// <summary> /// AES解密 /// </summary> /// <param name="decryptStr">密文</param> /// <param name="key">密钥</param> /// <returns></returns> protected string Decrypt(string decryptStr, string key) { var _aes = new AesCryptoServiceProvider(); _aes.BlockSize = 128; _aes.KeySize = 256; _aes.Key = Encoding.UTF8.GetBytes(key); _aes.IV = (byte[])(object)new sbyte[16];//Encoding.UTF8.GetBytes(IV); _aes.Padding = PaddingMode.PKCS7; _aes.Mode = CipherMode.CBC; var _crypto = _aes.CreateDecryptor(_aes.Key, _aes.IV); byte[] decrypted = _crypto.TransformFinalBlock( System.Convert.FromBase64String(decryptStr), 0, System.Convert.FromBase64String(decryptStr).Length); _crypto.Dispose(); return Encoding.UTF8.GetString(decrypted); }