System.Security.Cryptography.CryptographicException:RSACryptoserviceProvider 中的长度错误

Vai*_*hav 3 c# encryption rsa windows-phone-8

我想RSACryptoServiceProvider在 wp8 项目中使用c#加密和解密数据。我正在创建非对称密钥:

CspParameters parameters = new CspParameters();
parameters.KeyContainerName = "MyContainer";

RSACryptoServiceProvider provider = new RSACryptoServiceProvider(parameters);  
Run Code Online (Sandbox Code Playgroud)

现在我想加密数据。我在做:

CspParameters parameters = new CspParameters();

parameters.KeyContainerName = "MyContainer";
RSACryptoServiceProvider obj = new RSACryptoServiceProvider(parameters);
byte[] a = Generic.RSAEncrypt(ByteConverter.GetBytes(s[0]),
                              obj.ExportParameters(false), false); 

public static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo,
                                bool DoOAEPPadding)
{
    try {
        byte[] encryptedData;
        //Create a new instance of RSACryptoServiceProvider. 
        CspParameters parameters = new CspParameters();
        parameters.KeyContainerName = "TCSContainer";
        using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(parameters))
        {
            //Import the RSA Key information. This only needs 
            //to include 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;
    } catch (CryptographicException e) {
        //Catch and display a CryptographicException   
        //to the console. 
        //Console.WriteLine(e.Message);
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我在加密时遇到异常:

RSA.EncryptSystem.Security.Cryptography.CryptographicException : Bad length in RSACryptoserviceProvider. 
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪是:

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.RSACryptoServiceProvider.EncryptKey(SafeKeyHandle pKeyContext, Byte[] pbKey, Int32 cbKey, Boolean fOAEP, ObjectHandleOnStack ohRetEncryptedKey)
at System.Security.Cryptography.RSACryptoServiceProvider.Encrypt(Byte[] rgb, Boolean fOAEP)
at WindowsAppmart.Generic.RSAEncrypt(Byte[] DataToEncrypt, RSAParameters RSAKeyInfo, Boolean DoOAEPPadding)
Run Code Online (Sandbox Code Playgroud)

并且消息是错误长度。

我不明白我哪里出错了?

Ebb*_*sen 8

RSA仅用于加密少量数据。您可以加密的确切数量取决于密钥长度 + 填充使用的数量。1024 位密钥将允许多于 100 字节的位。

由于RSA非常慢,加密大消息的常用方法是使用混合加密。在混合加密中,您使用快速对称加密算法(如AES)用随机密钥加密数据。然后使用RSA对随机密钥进行加密,并与对称密钥加密数据一起发送。