怎么样用C#实现RSA加密?UP有分
流程是这样的,我先需要在证书里面读出公钥(已经实现),然后把需要加密的数据和公钥放到RSA里面加密。现在实现了在证书里提取公钥,但是我不知道怎么把这个公钥放到RSA里面去加密。以下是我在MSDN里看的代码,里面没有描述怎么用公钥对数据加密,请高手指点,如果有朋友做这个加密方面的可以加我QQ:1158281,大家一起讨论下。
static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.ImportParameters(RSAKeyInfo);
RijndaelManaged RM = new RijndaelManaged();
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
catch(CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo,bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch(CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
private void button1_Click(object sender, System.EventArgs e)
{
string certfile = @"e:\srvcert.crt";
X509Certificate cert = X509Certificate.CreateFromCertFile(certfile);
byte[] PublicKey = cert.GetPublicKey();//证书公钥
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
byte[] privatekey = Encoding.Default.GetBytes("aaaaaa");
byte[] dataToEncrypt = Encoding.Default.GetBytes("Data to Encrypt");
byte[] encryptedData;
byte[] decryptedData;
encryptedData = RSAEncrypt(dataToEncrypt,RSA.ExportParameters(true), false);
decryptedData = RSADecrypt(encryptedData,RSA.ExportParameters(true), false);
}