我想使用加密和解密数据RSACryptoServiceProvider
在 wp8 项目中的 c# 中。我正在创建非对称密钥:
CspParameters parameters = new CspParameters();
parameters.KeyContainerName = "MyContainer";
RSACryptoServiceProvider provider = new RSACryptoServiceProvider(parameters);
现在我想做加密数据。我在做:
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;
}
}
现在我在加密时遇到异常:
RSA.EncryptSystem.Security.Cryptography.CryptographicException : Bad length in RSACryptoserviceProvider.
堆栈跟踪是:
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)
并且消息长度错误。
我不明白我哪里会出错?