/*@file rsasample.cs
compiled ok with C#2005 by chinayaosir
本程序直接使用类库Cryptography实现RSA加解密演示
通用加解密原理
M=明文,C=密文,k1=加密钥匙,k2=解密钥匙
E=加密算法, D=解密算法
加密:C=Ek1(M)
解密:M=Dk2(C)=Dk2(Ek1(M))
k1==k2称为对称密码系统,精典代码是DES
k1<>k2称为非对称密码系统,精典代表是RSA
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace rsa
{
class Program
{
public static void Main()
{
try
{
string str_Plain_Text = "rsa with c#,very good!" ;
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("密文:/n" + str_Cypher_Text);
Console.WriteLine("公钥:/n" + str_Public_Key);
Console.WriteLine("私钥:/n" + str_Private_Key);
string str_Plain_Text2 = RSA_Decrypt(str_Cypher_Text, str_Private_Key);
Console.WriteLine("解密:" + str_Plain_Text2);
Console.ReadLine();
}
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);
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
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);
str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
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);
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//RSA.ImportParameters(RSAKeyInfo);
byte[] bytes_Public_Key = Convert.FromBase64String(str_Private_Key);
RSA.ImportCspBlob(bytes_Public_Key);
//OAEP padding is only available on Microsoft Windows XP or later.
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;
}
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}//end RSA_Decrypt
}
}