解决解密时出现"要解密的数据的长度无效" 或 "填充无效无法被移除" 的错误

1、首先排除数据库中读取加密后的字段是否被强制截断。

2、AES加密后的byte[]首先应用base64( Convert.ToBase64String)编码一次,若直接用utf8的话会报上述错误,若用unicode编码的话会解密成乱码,原因是加密后的byte数组用其他编码方式编码的话会丢失字符。

3、base编码后的字符串恢复为数组可用Convert.FromBase64String。

加密:

public static byte[] AESEncrypt(string plainText)
{
            SymmetricAlgorithm des = Rijndael.Create();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);            
            des.Key = Encoding.UTF8.GetBytes(keys);
            des.IV = _key1;

ICryptoTransform cTransform
= des.CreateEncryptor(); return cTransform.TransformFinalBlock(inputByteArray, 0, inputByteArray.Length); }

解密:

public static byte[] AESDecrypt(byte[] cipherText)
{
            SymmetricAlgorithm des = Rijndael.Create();
            des.Key = Encoding.UTF8.GetBytes(keys);
            des.IV = _key1;

            ICryptoTransform cTransform = des.CreateDecryptor();
            return cTransform.TransformFinalBlock(cipherText, 0, cipherText.Length);
}

 

public static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
public static string keys = "dongbinhuiasxiny";//密钥,128位        

 

转载于:https://www.cnblogs.com/fej121/p/3936291.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值