RSA 非对称加密

第一步:根据上面的原理性介绍,我们需要生成公钥(发信方需要)和私钥(收信方需要),实现代码如下:

//公钥在a.txt文件中,私钥在b.txt文件中.制造公钥和私钥的方法如下:
RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
string  publickey = crypt.ToXmlString(false);//公钥
string  privatekey = crypt.ToXmlString(true);//私钥
crypt.Clear();
//写入文本文件中
StreamWriter one = new StreamWriter(Server.MapPath("a.txt"),true,UTF8Encoding.UTF8);
one.Write(publickey);
StreamWriter two = new StreamWriter(Server.MapPath("b.txt"),true,UTF8Encoding.UTF8);
two.Write(privatekey);
one.Flush();
two.Flush();
one.Close();
two.Close();
Func.ShowPageMsg("成功保存公钥和密钥!");

 

第二步:发信方使用公钥对明文进行加密,实现代码如下:

StreamReader sr = new StreamReader(Server.MapPath("a.txt"), UTF8Encoding.UTF8);
string readpublickey = sr.ReadToEnd(); //包含 RSA 密钥信息的 XML 字符串。
sr.Close();
UTF8Encoding enc = new UTF8Encoding();
byte[] bytes = enc.GetBytes(TextBox1.Text.Trim());
RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
crypt.FromXmlString(readpublickey);
bytes = crypt.Encrypt(bytes, false);
string encryttext = Convert.ToBase64String(bytes);
string abb = Server.UrlEncode(encryttext);
Response.Write("密文为:" + abb);

 

第三步:收信方使用私钥对密文进行解密,实现代码如下:

StreamReader sr = new StreamReader(Server.MapPath("b.txt"), UTF8Encoding.UTF8);
string readprivatekey = sr.ReadToEnd();
sr.Close();
RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
UTF8Encoding enc = new UTF8Encoding();
byte[] bytes = Convert.FromBase64String(@Server.UrlDecode(TextBox1.Text.Trim()));
crypt.FromXmlString(readprivatekey);
byte[] decryptbyte = crypt.Decrypt(bytes, false);
string decrypttext = enc.GetString(decryptbyte);
Response.Write("明文为:" + decrypttext);

~~~~~~~~~~~~完毕【原】使用C#进行RSA(非对称)加密/解密

posted @ 2017-04-14 11:18  applekingghfhfhbr  阅读(168)  评论(0编辑  收藏  举报