RSA加密解密:私钥解密,公钥加密。
使用的命名空间:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
证书辅助类:
public sealed class DataCertificate
{
#region 生成证书
/// <summary>
/// 根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区)
/// </summary>
/// <param name="subjectName"></param>
/// <param name="makecertPath"></param>
/// <returns></returns>
//参数为:makecert -r -pe -n "cn=MyCA" -$ commercial -a sha1 -b 08/05/2010 -e 01/01/2012 -cy authority -ss my -sr currentuser
//其中各部分的意义:
//-r: 自签名
//-pe: 将所生成的私钥标记为可导出。这样可将私钥包括在证书中。
//-n "cn=MyCA": 证书的subject name,.net自带类库中有X509Store类,可以在store中根据证书subject name,来找到改证书
//store参考:X509Store 类
//-$ commercial:指明证书商业使用。。。
//-a:指定签名算法。必须是 md5(默认值)或 sha1。
//-b 08/05/2010:证书有效期的开始时间,默认为证书的创建日期。格式为:mm/dd/yyyy
//-e 01/01/2012:指定有效期的结束时间。默认为 12/31/2039 11:59:59 GMT。格式同上
//-ss my:证书产生到my个人store区
//-sr currentuser:保持到计算机当前个人用户区,其他用户登录系统后则看不到该证书。。
public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)
{
subjectName = "CN=" + subjectName;
//string param = " -pe -ss my -n \"" + subjectName + "\" ";
string param = " -r -pe -ss my -n \"" + subjectName + "\" " + " -a sha256 -b 01/01/2019 -e 01/01/4019";
try
{
Process p = Process.Start(makecertPath, param);
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
return false;
}
return true;
}
#endregion
#region 文件导入导出
/// <summary>
/// 从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
/// 并导出为pfx文件,同时为其指定一个密码
/// 并将证书从个人区删除(如果isDelFromstor为true)
/// </summary>
/// <param name="subjectName">证书主题,不包含CN=</param>
/// <param name="pfxFileName">pfx文件名</param>
/// <param name="password">pfx文件密码</param>
/// <param name="isDelFromStore">是否从存储区删除</param>
/// <returns></returns>
public static bool ExportToPfxFile(string subjectName, string pfxFileName,
string password, bool isDelFromStore)
{
subjectName = "CN=" + subjectName;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
foreach (X509Certificate2 x509 in storecollection)
{
if (x509.Subject == subj