1. 程式人生 > >C# AESCBC256 與 java AESCBC256 加解密

C# AESCBC256 與 java AESCBC256 加解密

created key rom post base bsp return block padding

和某上市公司對接接口,他們試用 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);
        }

C# AESCBC256 與 java AESCBC256 加解密