RSA非对称加密封装
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace AboutLicAuth
{
public class CryptRSA
{
/// <summary>
/// 对文件进行签名
/// </summary>
/// <param name="textToSign">文件</param>
/// <param name="priKeyFile">保存私钥的文件</param>
/// <returns>签名</returns>
public string SignAuth(string infoToSign, string priKeyFile)
{
string signKey = null;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
{
//获取密钥
string priKey = LoadKeyFromFile(priKeyFile);
rsa.FromXmlString(priKey);
RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
rsaFormatter.SetHashAlgorithm("SHA1");
byte[] strPlain = ASCIIEncoding.ASCII.GetBytes(infoToSign);
SHA1Managed sha = new SHA1Managed();
byte[] bytePlain = sha.ComputeHash(strPlain);
byte[] byteOfSign = rsaFormatter.CreateSignature(bytePlain);
signKey = Convert.ToBase64String(byteOfSign);
return signKey;
//return byteOfSign;
}
}
/// <summary>
/// 验证签名是否合法
/// </summary>
/// <param name="textToSign">文件</param>
/// <param name="signKey">签名</param>
/// <param name="pubKeyFile">保存公钥的文件</param>
/// <returns>签名是否合法</returns>
public bool CheckAuth(string strInfo,string signKey, string pubKeyFile)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
{
string pubKey = LoadKeyFromFile(pubKeyFile);
rsa.FromXmlString(pubKey);
RSAPKCS1SignatureDeformatter rsaDeFormatter = new RSAPKCS1SignatureDeformatter(rsa);
rsaDeFormatter.SetHashAlgorithm("SHA1");
byte[] byteInfo = ASCIIEncoding.ASCII.GetBytes(strInfo);
byte[] byteSignKey = Convert.FromBase64String(signKey);
SHA1Managed sha = new SHA1Managed();
byte[] byteHash = sha.ComputeHash(byteInfo);
bool isMatch = rsaDeFormatter.VerifySignature(byteHash,byteSignKey);
return isMatch;
}
}
//从文件中读出信息
protected string LoadKeyFromFile(string fileName)
{
StreamReader sr = new StreamReader(fileName);
string key = sr.ReadToEnd();
sr.Close();
return key;
}
}
/// <summary>
/// 产生工私钥文件
/// </summary>
public class GenarateRsaKey
{
/// <summary>
/// 产生公私钥对
/// </summary>
public static void GenKey()
{
string keyPairs=null;
string pubKey=null;
RSACryptoServiceProvider rsaprd = new RSACryptoServiceProvider();
keyPairs = rsaprd.ToXmlString(true);
pubKey = rsaprd.ToXmlString(false);
SaveKeyToFile("key.xml", keyPairs);
SaveKeyToFile("pubKey.xml", pubKey);
}
protected static void SaveKeyToFile(string fileName, string data)
{
StreamWriter sw = new StreamWriter(fileName);
sw.Write(data);
sw.Close();
}
public string LoadKeyFromFile(string fileName)
{
StreamReader sr = new StreamReader(fileName);
string key = sr.ReadToEnd();
sr.Close();
return key;
}
}
}