C# 加密-RSA

RSA 实际应用中是:接收方产生公钥和私钥,发送方用其公钥加密,再把加密后的内容发送给接收方。

CspParameters 的名称空间是:

System.Security.Cryptography
CspParameters cpSend = new CspParameters(); //Csp = Cryptography Service Provider
CspParameters cpReceive = new CspParameters();
cpSend.KeyContainerName = "SendTestContainer";
cpReceive.KeyContainerName = "ReceiveTestContainer";

RSACryptoServiceProvider rsaSend = new RSACryptoServiceProvider(cpSend); ;
RSACryptoServiceProvider rsaReceive = new RSACryptoServiceProvider(cpReceive);

rsaSend.FromXmlString(rsaReceive.ToXmlString(false)); //发送方使用接收方给它的公钥进行加密

string plaintext = "前几天我碰到一个朋友,约我跟马贼打架,我立马答应了他,因为我觉得这件事好无聊。";
byte[] ciphertext = rsaSend.Encrypt(System.Text.Encoding.UTF8.GetBytes(plaintext), false); //加密后
byte[] decryption = rsaReceive.Decrypt(ciphertext, false); //解密后

lbl.Width = 760;
lbl.Text = "";
lbl.Text += Convert.ToBase64String(ciphertext) + "<br />"; //显示加密后的
lbl.Text += System.Text.Encoding.UTF8.GetString(decryption) + "<br />"; //显示解密后的
lbl.Text += Server.HtmlEncode(rsaSend.ToXmlString(false)) + "<br />"; //显示发送方公钥
lbl.Text += Server.HtmlEncode(rsaReceive.ToXmlString(true)) + "<br />"; //显示接收方公钥和私钥
lbl.Text += Server.HtmlEncode(rsaReceive.ToXmlString(false)) + "<br />";  //显示接收方公钥

rsaSend.PersistKeyInCsp = true; //密钥要保存起来
//rsaSend.Clear();
rsaReceive.PersistKeyInCsp = true;
//rsaReceive.Clear();

在上面的代码中,我们使用 CspParameters 将密钥保存起来,ToXmlStringFromXmlString 将接收方的公钥告诉给发送方。

posted on 2009-11-30 11:12  冬日阳光  阅读(1154)  评论(0编辑  收藏  举报

导航