c# Rsa解密抛出“坏数据”;例外

本文关键字:坏数据 数据 例外 Rsa 解密 | 更新日期: 2023-09-27 18:02:23

我使用微软的RSACryptoServiceProvider类加密/解密数据。然而,解密函数抛出一个异常"坏数据"。是否每次使用加密/解密时都要创建提供程序类的新实例?

RSA提供程序类

 static public byte[] RSAEncrypt(byte[] byteEncrypt, RSAParameters RSAInfo, bool isOAEP)
    {
        try
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportParameters(RSAInfo);
                //Encrypt the passed byte array and specify OAEP padding.
                return RSA.Encrypt(byteEncrypt, isOAEP);
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
    }
    static public byte[] RSADecrypt(byte[] byteDecrypt, RSAParameters RSAInfo, bool isOAEP)
    {
        try
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096))
            {
                //Import the RSA Key information. This needs
                //to include the private key information.
                RSA.ImportParameters(RSAInfo);
                //Decrypt the passed byte array and specify OAEP padding.
                return RSA.Decrypt(byteDecrypt, isOAEP);
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.ToString());
            return null;
        }
    }
}
使用

  UnicodeEncoding ByteConverter = new UnicodeEncoding();
  RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096);
  byte[] plainPassword;
  byte[] encryptedPassword;
  plainPassword = ByteConverter.GetBytes(connectionStringPasswordTextBox.Text);
  encryptedPassword = CryptoHelper.RSAEncrypt(plainPassword, RSA.ExportParameters(false), false);
  RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(4096);
  byte[] decryptedPassword = CryptoHelper.RSADecrypt(Convert.FromBase64String(connectionString.password), RSA.ExportParameters(true), false);

编辑

重试几次后,异常变为"The parameter is incorrect"。我认为这与创建rsa类的实例,而不是每次使用它创建一个新的。

c# Rsa解密抛出“坏数据”;例外

RSACryptoServiceProvider(int)构造函数生成一个新密钥(除非CAPI为null-name返回一个密钥;我不确定这是否可能)。所以这个代码是用一个密钥加密,并试图用另一个密钥解密。结果的答案没有什么意义,因此会抛出异常。

    生成你的密钥一次,并保存其中的rsparameters。
  • 为了使你的代码更易于移植,避免使用"RSACryptoServiceProvider";如果可能的话,只讨论RSA。
    • 不幸的是,密钥创建是不可能的,因为RSACryptoServiceProvider在KeySize更改时不会生成新密钥。

所以你应该在。net 4.6或更高版本中使用这样的东西:

public static byte[] RSAEncrypt(
    byte[] byteEncrypt,
    RSAParameters rsaInfo,
    RSAEncryptionPadding padding)
{
    try
    {
        using (RSA rsa = RSA.Create())
        {
            rsa.ImportParameters(rsaInfo);
            return rsa.Encrypt(byteEncrypt, padding);
        }
    }
    catch (CryptographicException e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
}