You need to enable JavaScript to run this app. C# AES解密抛出Padding is invalid and cannot be removed错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

C# AES解密抛出Padding is invalid and cannot be removed错误如何解决

问题核心原因

  • 密文编码转换逻辑错误:加密完成后你通过BitConverter.ToString(dest).Replace("-","")将密文字节转为了十六进制字符串,但解密时直接调用Encoding.UTF8.GetBytes(encstr)把十六进制字符串转字节,该操作不符合十六进制字符串转原始字节的规则,传给解密函数的字节并非真实密文字节,自然会触发填充错误。
  • Decrypt方法存在逻辑错误:方法内已经将解密结果存到了result变量,但最终返回的是未赋值的plaintext变量,即使转换逻辑修复也无法拿到正确解密结果。

修复方案

1. 新增十六进制字符串转原始字节的公共方法

public static byte[] HexStringToBytes(string hexStr)
{
    byte[] bytes = new byte[hexStr.Length / 2];
    for (int i = 0; i < bytes.Length; i++)
    {
        bytes[i] = Convert.ToByte(hexStr.Substring(i * 2, 2), 16);
    }
    return bytes;
}

2. 修复Main方法的解密调用逻辑

可以选择直接调用已经实现正确的DecryptUsingAes方法,不需要额外用存在bug的Decrypt方法:

static void Main(string[] args)
{
    string key = "ldm_encrypt_code1234567891234567";
    string IV = "9876897123651785";
    string encstr = BaseEncryptor.EncryptUsingAes(Encoding.UTF8.GetBytes(@"Hello Code"), Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(IV)); 
    // 解密前先把十六进制密文字符串转回原始密文字节
    string decResult = BaseEncryptor.DecryptUsingAes(HexStringToBytes(encstr), Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(IV));
}

3. 若要使用Decrypt方法,修正返回值错误

把Decrypt方法末尾的return plaintext;改为return result;即可,多余的plaintext变量可以直接删除。


内容的提问来源于stack exchange,提问作者mahmoud sayed abdo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 23:36:03