非对称加密类

摘自http://topic.csdn.net/u/20101231/09/039bdd22-3f0a-4bbb-908e-d887b4d7bbfe.html?19933

using System;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// 非对称加密类
/// </summary>
public static class AsymmetricEncrytClass
{
#region 自动生成公钥、私钥方法
/// <summary>
/// 自动生成非对称公钥、私钥
/// </summary>
/// <param name="publicKey">返回的公钥</param>
/// <param name="privateKey">返回的私钥</param>
public static void GenerateKey(out string publicKey, out string privateKey)
{
RSACryptoServiceProvider rsa
= new RSACryptoServiceProvider();
publicKey
= rsa.ToXmlString(false);
privateKey
= rsa.ToXmlString(true);
}

#endregion
#region 非对称加密代码
/// <summary>
/// 非对称加密方法
/// </summary>
/// <param name="strMsg">要加密的数据</param>
/// <param name="strPublicKey">加密的公钥</param>
/// <returns>返回加密后的byte[]数据</returns>
public static byte[] AsymmetricEncryptRSAFunction(this string strMsg, string strPublicKey)
{
RSACryptoServiceProvider rsa
= new RSACryptoServiceProvider();
rsa.FromXmlString(strPublicKey);
byte[] buffers = Encoding.UTF8.GetBytes(strMsg);
byte[] encryBuffer;
try
{
encryBuffer
= rsa.Encrypt(buffers, false);
}
catch
{
return null;
}
return encryBuffer;
}
#endregion
#region 非对称解密代码
/// <summary>
/// 非对称解密方法
/// </summary>
/// <param name="byteMsg">需要解密的byte[]类型数据</param>
/// <param name="strPrivateKey">解密的私钥</param>
/// <returns>解密后的数据string类型</returns>
public static string AsymmetricDecryptRSAFunction(this byte[] byteMsg, string strPrivateKey)
{
RSACryptoServiceProvider rsa
= new RSACryptoServiceProvider();
rsa.FromXmlString(strPrivateKey);
byte[] decryptBuffers;
try
{
decryptBuffers
= rsa.Decrypt(byteMsg, false);
}
catch (Exception e)
{
return e.Message;
}
return Encoding.UTF8.GetString(decryptBuffers);
}
#endregion
}

posted @ 2011-04-12 13:16  梦幻泡影  阅读(255)  评论(0编辑  收藏  举报