Error: "Padding is invalid and cannot be removed" using asymmetric algorithm

Error: "Padding is invalid and cannot be removed" using asymmetric algorithm

我想使用非对称加密算法加密和解密字符串,即我想在加密和解密函数中传递不同的密钥。

我的代码如下:

public ActionResult Encrypt(string clearText)
{
    string EncryptionKey = "ABKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }

    Decrypt(clearText);

    return View(clearText); 
}

public string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        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);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText ;
}

这是我使用 link 发送值的加密函数 如下

 <a href="@Url.Action("Encrypt", "Home", new {@clearText="5"})">Bid Buddy</a>

这里我想发送不同的键值,如图所示。

您的 encrpt / decrpyt keys 不同,导致您收到此错误。

Padding is invalid and cannot be removed

确保encrpt / decrpt 相同

AES 是一种对称分组密码。解密 只有 在加密过程中提供相同的密钥时才有效。没有办法解决这个问题。

您还拥有一个加密哈希函数。所有散列函数都存在冲突,但对于像您这样的加密散列函数而言,这些冲突的利用可以忽略不计。因此,找到映射到同一密钥的两个密码(这将使其在技术上不对称)的成本太高。

您需要生成一个public-私钥对。这样做的一个选项是例如 RSA。然后,您将使用随机 AES 密钥加密数据,并使用 RSA public 密钥加密此 AES 密钥。这叫做hybrid encryption.