C#使用AES/ECB/PKCS5Padding加密解密

与JAVA AES/ECB/PKCS5Padding加密解密相同效果,但是c#里面没有PKCS5Padding,可以使用PKCS7,效果是一样的
封装代码如下:

        /// 
        ///  AES 加密
        /// 
        /// 明文
        /// 密钥
        /// 
        public static string AesEncrypt(string str, string aesKey)
        {
            string data = string.Empty;
            if (!string.IsNullOrEmpty(str) && !string.IsNullOrEmpty(aesKey))
            {
                byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
                using(Aes aes = Aes.Create())
                {
                    var iv = new byte[16];
                    for (int i = 0; i < iv.Length; i++)
                        iv[i] = 0;
                    aes.IV = iv;
                    aes.Key = Encoding.UTF8.GetBytes(aesKey);
                    aes.Mode = CipherMode.ECB;
                    aes.Padding = PaddingMode.PKCS7;
                    aes.BlockSize = 128;
                    var cryptoTransform = aes.CreateEncryptor();
                    var resultArray = cryptoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                    data = Convert.ToBase64String(resultArray, 0, resultArray.Length);

                }
            }
            return data;
        }

        /// 
        ///  AES 解密
        /// 
        /// 密文
        /// 密钥
        /// 
        public static string AesDecrypt(string str, string aesKey)
        {
            string data = string.Empty;
            if (!string.IsNullOrEmpty(str) && !string.IsNullOrEmpty(aesKey))
            {
                byte[] toEncryptArray = Convert.FromBase64String(str);
                using (Aes aes = Aes.Create())
                {
                    var iv = new byte[16];
                    for (int i = 0; i < iv.Length; i++)
                        iv[i] = 0;
                    aes.IV = iv;
                    aes.Key = Encoding.UTF8.GetBytes(aesKey);
                    aes.Mode = CipherMode.ECB;
                    aes.Padding = PaddingMode.PKCS7;
                    aes.BlockSize = 128;
                    var cryptoTransform = aes.CreateDecryptor();
                    byte[] resultArray = cryptoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                    data = Encoding.UTF8.GetString(resultArray);
                }
                    
            }
            return data;
        }

你可能感兴趣的:(c#知识积累,c#,AES加密)