首页 > 解决方案 > 填充无效且无法删除 - 解密问题

问题描述

我正在尝试使用以下方法解密内容

public string DecryptContent(string data)
{
    string decryptedContent = data;       
    try
    {
       byte[] cipherBytes = Convert.FromBase64String(decryptedContent);
       using (Aes encryptor = Aes.Create())
       {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_secretKey, 
                                         Encoding.ASCII.GetBytes(_secretSalt));

            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = 
                 new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                 }
    
                 decryptedContent = Encoding.Unicode.GetString(ms.ToArray());
             }
         }
     }
     catch (Exception e)
     {
        // {"Padding is invalid and cannot be removed."}  <--- THROWS AN EXCEPTION
     }

     return decryptedContent;
}

我试图添加

encryptor.Padding = PaddingMode.Zeros

但是由于这种方法,这会产生一些奇怪的中文,例如字母

也试过

 encryptor.Padding = PaddingMode.PKCS7

但仍然出现异常!

有任何想法吗?

标签: c#.net-core

解决方案


推荐阅读