/**//*
* 基于RSA的加密/解密示例C#代碼
* (采用字元串作為參數)RSA_Demo2
*
* 夏春濤 Email:[email protected]
* Blog:http://bluesky521.cnblogs.com
* 運作環境:.net2.0 framework
* 備注:
* 不對稱算法通常用于加密少量資料,如加密對稱密鑰和 IV。通常,
* 執行不對稱加密的個人使用由另一方生成的公鑰。.NET Framework
* 為此目的而提供了 RSACryptoServiceProvider 類。
*/
using System;
using System.Security.Cryptography;
using System.Text;
class RSACSPSample
{
static void Main()
try
string str_Plain_Text = "How are you?How are you?How are you?How are you?=-popopolA";
Console.WriteLine("明文:" + str_Plain_Text);
Console.WriteLine("長度:" + str_Plain_Text.Length.ToString());
Console.WriteLine();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
string str_Public_Key;
string str_Private_Key;
string str_Cypher_Text = RSA_Encrypt(str_Plain_Text, out str_Public_Key,out str_Private_Key);
Console.WriteLine("密文:" + str_Cypher_Text);
Console.WriteLine("公鑰:" + str_Public_Key);
Console.WriteLine("私鑰:" + str_Private_Key);
string str_Plain_Text2 = RSA_Decrypt(str_Cypher_Text, str_Private_Key);
Console.WriteLine("解密:" + str_Plain_Text2);
}
catch (ArgumentNullException)
Console.WriteLine("Encryption failed.");
}
//RSA加密,随機生成公私鑰對并作為出參傳回
static public string RSA_Encrypt(string str_Plain_Text, out string str_Public_Key, out string str_Private_Key)
str_Public_Key = "";
str_Private_Key = "";
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToEncrypt = ByteConverter.GetBytes(str_Plain_Text);
str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
//OAEP padding is only available on Microsoft Windows XP or later.
byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false);
string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text);
return str_Cypher_Text;
catch (CryptographicException e)
Console.WriteLine(e.Message);
return null;
//RSA解密
static public string RSA_Decrypt(string str_Cypher_Text, string str_Private_Key)
byte[] DataToDecrypt = Convert.FromBase64String(str_Cypher_Text);
//RSA.ImportParameters(RSAKeyInfo);
byte[] bytes_Public_Key = Convert.FromBase64String(str_Private_Key);
RSA.ImportCspBlob(bytes_Public_Key);
byte[] bytes_Plain_Text = RSA.Decrypt(DataToDecrypt, false);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
string str_Plain_Text = ByteConverter.GetString(bytes_Plain_Text);
return str_Plain_Text;
Console.WriteLine(e.ToString());
}
備注:經測試明文長度超過58時會出現異常.