CSDN博客

img keenx

使用C#+ASP.NET来进行RSA(非对称)加密.

发表于2004/6/22 21:14:00  1023人阅读

加密:

<%@ Page language="c#" AutoEventWireup="false"%>
<%@ Import Namespace= "System.Security.Cryptography" %>
<%@ Import Namespace= "System.IO" %>
<%@ Import Namespace= "System.Text" %>

<%
string word = Request.Params["word"];
if(word == null){
 Response.Write("没有输入密码啦!!!");
 return;
}
 
StreamReader sr = new StreamReader(@"f:/a.txt",UTF8Encoding.UTF8);
string readpublickey = sr.ReadToEnd();
sr.Close();
 
RSACryptoServiceProvider crypt=new RSACryptoServiceProvider();
UTF8Encoding enc=new UTF8Encoding();
byte[] bytes=enc.GetBytes(word);
crypt.FromXmlString(  readpublickey );
bytes = crypt.Encrypt( bytes,false );
string encryttext=Convert.ToBase64String(bytes);
string abb = Server.UrlEncode(encryttext);
Response.Write(abb);

Response.Write("<a href='take.aspx?word=" + encryttext + "'>" + encryttext + @"</a>");
%>

解密:

<%@ Page language="c#" AutoEventWireup="false"%>
<%@ Import Namespace= "System.Security.Cryptography" %>
<%@ Import Namespace= "System.IO" %>
<%@ Import Namespace= "System.Text" %>

<%
string word = Request.QueryString["word"];
if(word == null){
 Response.Write("没有传来密码啦!!!");
 return;
}
 
StreamReader sr = new StreamReader(@"f:/b.txt",UTF8Encoding.UTF8);
string readprivatekey  = sr.ReadToEnd();
sr.Close(); 

Response.Write("<br>" + word);

RSACryptoServiceProvider crypt=new RSACryptoServiceProvider();
UTF8Encoding enc=new UTF8Encoding();
byte[] bytes = Convert.FromBase64String(@word);
crypt.FromXmlString ( readprivatekey ) ;
byte[] decryptbyte = crypt.Decrypt( bytes,false );
string decrypttext=enc.GetString( decryptbyte );

Response.Write(decrypttext);

%>

公匙在a.txt文件中,私匙在b.txt文件中.

制造公匙和私匙的方法如下:

crypt=new RSACryptoServiceProvider();
publickey=crypt.ToXmlString(false);//公匙
privatekey=crypt.ToXmlString(true);//私匙
crypt.Clear();

//写入文本文件中
StreamWriter one=new StreamWriter(@"f:/a.txt",true,UTF8Encoding.UTF8);
one.Write(publickey);
StreamWriter two=new StreamWriter(@"f:/b.txt",true,UTF8Encoding.UTF8);
two.Write(privatekey);
one.Flush();
two.Flush();
one.Close();
two.Close();
MessageBox.Show("成功保存公匙和密匙!");

0 0

相关博文

我的热门文章

img
取 消
img