0
点赞
收藏
分享

微信扫一扫

C# AES加密报错:填充无效,无法被移除

属性设置在加密解密时不一致出现“填充无效,无法被移除”的错误。但是这只是其中的一个原因。

rDel.Key = resultArray;

rDel.BlockSize = 128;

rDel.Mode = CipherMode.ECB;

rDel.Padding = PaddingMode.Zeros;

C# AES加密报错:填充无效,无法被移除_加解密

加解密属性名一致还是报错

C# AES加密报错:填充无效,无法被移除_加密解密_02

交初始key的位置互换正常。具体是初始化属性有先后顺序

代码如下:

 public static string AesEncrypt(string str, string key)

       {

           if (string.IsNullOrEmpty(str)) return null;

           Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

           System.Security.Cryptography.RijndaelManaged rm = new

           System.Security.Cryptography.RijndaelManaged

           {

               BlockSize =128,

               KeySize=256,

               Key = Encoding.UTF8.GetBytes(key),

               Mode = System.Security.Cryptography.CipherMode.ECB,

               Padding = System.Security.Cryptography.PaddingMode.PKCS7,

           };

           System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();

           Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

           return Convert.ToBase64String(resultArray, 0, resultArray.Length);

       }

       public static string AesDecrypt(string str, string key)

       {

           if (string.IsNullOrEmpty(str)) return null;

           Byte[] toEncryptArray = Convert.FromBase64String(str);

           System.Security.Cryptography.RijndaelManaged rm = new

           System.Security.Cryptography.RijndaelManaged

           {

               BlockSize = 128,

               KeySize = 256,

               Key = Encoding.UTF8.GetBytes(key),

               Mode = System.Security.Cryptography.CipherMode.ECB,

               Padding = System.Security.Cryptography.PaddingMode.PKCS7

           };

           System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();

           Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

           return Encoding.UTF8.GetString(resultArray);

       }

举报

相关推荐

0 条评论