protected void Page_Load(object sender, EventArgs e)
{
//私钥
string pri = "";
//公钥
string pub = "";
//明文
string m = "I love you!";
//生成公钥和私钥
RSAKey(out pri, out pub);
//用公钥生成密文
string mi = RSAEncrypt(pub, m);
//用私钥解密密文
string ming = RSADecrypt(pri, mi);
Response.Write("私钥:"+pri+"/n");
Response.Write("公钥:" + pub + "/n");
Response.Write("密文:" + mi + "/n");
Response.Write("明文:" + ming);
}
//RSA的加密函数
public string RSAEncrypt(string xmlPublicKey, string EncryptString)
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(EncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
//RSA的解密函数
public string RSADecrypt(string xmlPrivateKey, string DecryptString)
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
PlainTextBArray = Convert.FromBase64String(DecryptString);
DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
//RSA 的密钥产升
//产生私钥 和公钥
public void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
xmlKeys = rsa.ToXmlString(true);
xmlPublicKey = rsa.ToXmlString(false);
}