3

我有一个要求,我需要在一个应用程序中加密我的连接字符串并在另一个应用程序中解密它。考虑到这一点,我将公钥和私钥分别保存在应用程序的 App.Config 中。

现在,RSA 不应该给我相同的加密字符串和我使用的相同密钥吗?

我总是得到不同的加密字符串,使用相同的密钥。!!请帮助我消除混乱。我不明白如何解决这个问题,如果我使用保存的加密字符串,我会得到BAD Data异常,因为每次加密都会给我不同的加密字符串。

这是我的代码:

private string connecString;
private RSACryptoServiceProvider rsaEncryptDecrypt;

public EncryptAndDecrypt(string connecString)
{
    this.connecString = connecString;
    this.rsaEncryptDecrypt = new RSACryptoServiceProvider(4096);
}

public string EncryptTheConnecString(string publicKeyValue)
{
    byte[] encryptedData;
    rsaEncryptDecrypt.FromXmlString(publicKeyValue);

    byte[] message = Encoding.UTF8.GetBytes(connecString);
    encryptedData = rsaEncryptDecrypt.Encrypt(message, false);

    return Convert.ToBase64String(encryptedData);
}

public string DecryptTheConnecString(string privateKeyValue, string encrystr)
{
    byte[] decryptedData;
    rsaEncryptDecrypt.FromXmlString(privateKeyValue);

    byte[] message = Convert.FromBase64String(encrystr);
    decryptedData = rsaEncryptDecrypt.Decrypt(message, false);

    return Encoding.UTF8.GetString((decryptedData));
}

先感谢您。

更新1: 我用过

UnicodeEncoding ByteConverter = new UnicodeEncoding();
ByteConverter.GetBytes("data to encrypt");
//Which is not Connection string but a small test str

我仍然看到加密数据每次都在变化。 但是不再出现Bad Data错误。但是我不能在Encoding.UTF8上使用UTF16(UnicodeEncoding)因为它不能加密像连接字符串这样的巨大字符串并抛出异常:

 CryptographicException: Key not valid for use in specified state.

更新 2:

UTF8Encoding ByteConverter = new UTF8Encoding();我可以通过使用然后做来解决坏数据的问题ByteConverter .GetString("HUGE STRING");

4

2 回答 2

6

它可能由于Random Padding发生。

于 2012-02-29T04:41:29.880 回答
2

一般来说,你的问题的答案是肯定的,如果给出相同的参数,它应该总是产生相同的结果。

解决这些问题的最佳方法是尽可能接近最佳实践代码,目前您使用的加密提供程序与框架文档建议的略有不同,请参见以下内容:

static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
    byte[] encryptedData;
    //Create a new instance of RSACryptoServiceProvider.
    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
    {

        //Import the RSA Key information. This only needs
        //toinclude the public key information.
        RSA.ImportParameters(RSAKeyInfo);

        //Encrypt the passed byte array and specify OAEP padding.  
        //OAEP padding is only available on Microsoft Windows XP or
        //later.  
        encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
    }
    return encryptedData;
}

这是官方 MSDN 文档的摘录:http:
//msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx

首先尝试采用最佳实践,然后看看这个问题是否仍然出现。

于 2012-02-28T15:29:51.387 回答