C#使用证书做数字签名,RSA加密解密,X509【.NET】
关键字:.NET证书签名RSA加密解密 X509Certificate2楼主最近做WebService接口,其中为了安全起见,我们接口参数使用CA证书做了签名,其中两个重要的方法是签名和签名验证,此签名加密是不可逆向解开的,如果没有CA证书,自己用C#创建一个证书也可以用。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
/************************
* 说明:接口数字签名类
* 创建人:原道楠
* 创建时间:2016-5-19
* **********************/
namespace Common.PayMentPlatform
{
/// <summary>
/// 接口数字签名类
/// </summary>
public class Signature
{
/// <summary>
/// 数字签名
/// </summary>
/// <param name="plaintext">明文</param>
/// <returns>签名</returns>
public static string HashAndSignString(string plaintext)
{
//根据证书友好名称查找证书
X509Certificate2 x509Certificate2 = GetX509Certificate2();
if (x509Certificate2 != null)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
//将明文转byte[]
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
//将证书中私钥转为rsa对象
RSACryptoServiceProvider RSAalg = x509Certificate2.PrivateKey as RSACryptoServiceProvider;
//使用SHA1哈希进行摘要算法,
byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());
//得到签名
string signStr = Convert.ToBase64String(encryptedData);
RSAalg.Clear();
RSAalg.Dispose();
return signStr;
}
else
{
//找不到证书记录日志到本地,没有的可以删掉
Helper.WriteLogContent("签名时在系统中找不到证书,明文:" + plaintext);
return "";
}
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="signedData">签名</param>
/// <returns></returns>
public static bool VerifySigned(string plaintext, string signedData)
{
//根据证书友好名称查找证书
X509Certificate2 x509Certificate2 = GetX509Certificate2();
if (x509Certificate2 != null)
{
//将证书公钥转为rsa对象
RSACryptoServiceProvider RSAalg = x509Certificate2.PublicKey.Key as RSACryptoServiceProvider;
UnicodeEncoding ByteConverter = new UnicodeEncoding();
//将明文转byte[]
byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext);
//将签名转byte[]
byte[] signedDataBytes = Convert.FromBase64String(signedData);
//验证签名
bool isSuccess = RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes);
RSAalg.Clear();
RSAalg.Dispose();
return isSuccess;
}
else
{
//找不到证书记录日志到本地,没有的可以删掉
Helper.WriteLogContent( "验证签名时在系统中找不到证书,明文:" + plaintext + ",密文:" + signedData);
return false;
}
}
/// <summary>
/// 获取证书对象 (楼主这用的是物理路径获取证书)
/// </summary>
/// <returns>为null即找不到证书</returns>
public static X509Certificate2 GetX509Certificate2()
{//证书路径和密码放到了配置文件里 第一个参数是证书的绝对路径,第二个是证书密码,没有就空
return new X509Certificate2(ConfigurationManager.AppSettings["CerPath"], ConfigurationManager.AppSettings["CerPassword"]);
}
}
}
关键字:.NET证书签名RSA加密解密 X509Certificate2
真好谢谢分享
页:
[1]