日期:2009-11-23  浏览次数:20374 次

此Demo包含两个文件,建立一个解决方案,然后建立两个文件,一个为Form,一个为Class,把代码分别复制进去即可

RSA正确的执行过程:

加密解密:
1、获取密钥,这里是产生密钥,实际应用中可以从各种存储介质上读取密钥
2、加密
3、解密
签名和验证:
签名:
1、获取密钥,这里是产生密钥,实际应用中可以从各种存储介质上读取密钥
2、获取待签名的Hash码
3、签名
其中,1和2的步骤无所谓,在本例中,我们将对txtSource里的内容进行签名,也可以对文件进行签名
验证签名:
1、获取密钥,这里是产生密钥,实际应用中可以从各种存储介质上读取密钥
2、获取待验证签名的Hash码
3、获取签名的字串,这里签名的字串存储在m_strEncryptedSignatureData变量中,在DEMO中必须通过签名才能获得这个字串,因此需要先执行签名,当然也可以更改之后通过别的方式获得
4、验证
其中,1和2的步骤无所谓,在本例中,我们将对txtSource里的内容进行签名验证,也可以对文件进行签名验证
如果是文件,取得文件之后把文件的内容以byte[]的方式代入即可
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//RSACryption.cs
///////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Text;
using System.Security.Cryptography;

namespace RSAApplication
{
/// <summary>
/// RSACryption 的摘要说明。
/// </summary>
public class RSACryption
{
#region 构造函数

public RSACryption()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
#endregion

#region RSA 加密解密

#region RSA 的密钥产生
//RSA 的密钥产生
//产生私钥 和公钥
public void RSAKey(out string XMLKeys,out string XMLPublicKey)
{
try
{
System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
XMLKeys=rsa.ToXMLString(true);
XMLPublicKey = rsa.ToXMLString(false);
}
catch(Exception ex)
{
throw ex;
}
}
#endregion
#region RSA的加密函数
//##############################################################################
//RSA 方式加密
//说明KEY必须是XML的行式,返回的是字符串
//在有一点需要说明!!该加密方式有 长度 限制的!!
//##############################################################################

//RSA的加密函数
public string RSAEncrypt(string XMLPublicKey,string m_strEncryptString )
{
try
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
rsa.FromXMLString(XMLPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result=Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch(Exception ex)
{
throw ex;
}
}
//RSA的加密函数
public string RSAEncrypt(string XMLPublicKey,byte[] EncryptString )
{
try
{
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
rsa.FromXMLString(XMLPublicKey);
CypherTextBArray = rsa.Encrypt(EncryptString, false);
Result=Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch(Exception ex)
{
throw ex;
}
}
#endregion

#region RSA的解密函数
//RSA的解密函数
public string RSADecrypt(string XMLPrivateKey, string m_strDecryptString )
{
try
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
rsa.FromXMLString(XMLPrivateKey);
PlainTextBArray =Convert.FromBase64String(m_strDecryptString);
DypherTextBArray=rsa.Decrypt(PlainTextBArray, false);
Result=(new UnicodeEncoding()).GetString(DypherTextBArray);