(转)C#创建数字证书并导出为pfx,并使用pfx进行非对称加解密
我的项目当中,考虑到安全性,需要为每个客户端分发一个数字证书,同时使用数字证书中的公私钥来进行数据的加解密。为了完成这个安全模块,特写了如下一个DEMO程序,该DEMO程序包含的功能有:
1:调用.NET2.0的MAKECERT创建含有私钥的数字证书,并存储到个人证书区;
2:将该证书导出为pfx文件,并为其指定一个用来打开pfx文件的password;
3:读取pfx文件,导出pfx中公钥和私钥;
4:用pfx证书中的公钥进行数据的加密,用私钥进行数据的解密;
代码如下:
/// 将证书从证书存储区导出,并存储为pfx文件,同时为pfx文件指定打开的密码
/// 本函数同时也演示如何用公钥进行加密,私钥进行解密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_toPfxFile_Click(object sender, EventArgs e)
{
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 == "CN=luminji")
{
Debug.Print(string.Format("certificate name: {0}", x509.Subject));
byte[] pfxByte = x509.Export(X509ContentType.Pfx, "123");
using (FileStream fileStream = new FileStream("luminji.pfx", FileMode.Create))
{
// Write the data to the file, byte by byte.
for (int i = 0; i < pfxByte.Length; i++)
fileStream.WriteByte(pfxByte[i]);
// Set the stream position to the beginning of the file.
fileStream.Seek(0, SeekOrigin.Begin);
// Read and verify the data.
for (int i = 0; i < fileStream.Length; i++)
{
if (pfxByte[i] != fileStream.ReadByte())
{
Debug.Print("Error writing data.");
return;
}
}
fileStream.Close();
Debug.Print("The data was written to {0} " +
"and verified.", fileStream.Name);
}
string myname = "my name is luminji! and i love huzhonghua!";
string enStr = this.RSAEncrypt(x509.PublicKey.Key.ToXmlString(false), myname);
MessageBox.Show("密文是:" + enStr);
string deStr = this.RSADecrypt(x509.PrivateKey.ToXmlString(true), enStr);
MessageBox.Show("明文是:" + deStr);
}
}
store.Close();
store = null;
storecollection = null;
}
/// <summary>
/// 创建还有私钥的证书
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_createPfx_Click(object sender, EventArgs e)
{
string MakeCert = "C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\Bin\\makecert.exe";
string x509Name = "CN=luminji";
string param = " -pe -ss my -n \"" + x509Name + "\" " ;
Process p = Process.Start(MakeCert, param);
p.WaitForExit();
p.Close();
MessageBox.Show("over");
}
/// <summary>
/// 从pfx文件读取证书信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_readFromPfxFile(object sender, EventArgs e)
{
X509Certificate2 pc = new X509Certificate2("luminji.pfx", "123");
MessageBox.Show("name:" + pc.SubjectName.Name);
MessageBox.Show("public:" + pc.PublicKey.ToString());
MessageBox.Show("private:" + pc.PrivateKey.ToString());
pc = null;
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="xmlPrivateKey"></param>
/// <param name="m_strDecryptString"></param>
/// <returns></returns>
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(xmlPrivateKey);
byte[] rgb = Convert.FromBase64String(m_strDecryptString);
byte[] bytes = provider.Decrypt(rgb, false);
return new UnicodeEncoding().GetString(bytes);
}
/// <summary>
/// RSA加密
/// </summary>
/// <param name="xmlPublicKey"></param>
/// <param name="m_strEncryptString"></param>
/// <returns></returns>
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(xmlPublicKey);
byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
return Convert.ToBase64String(provider.Encrypt(bytes, false));
}
上文是一个示例程序,一个完整的证书工具类如下:
2 public sealed class DataCertificate
3 {
4 #region 生成证书
5 /// <summary>
6 /// 根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区)
7 /// </summary>
8 /// <param name="subjectName"></param>
9 /// <param name="makecertPath"></param>
10 /// <returns></returns>
11 public static bool CreateCertWithPrivateKey(string subjectName, string makecertPath)
12 {
13 subjectName = "CN=" + subjectName;
14 string param = " -pe -ss my -n \"" + subjectName + "\" ";
15 try
16 {
17 Process p = Process.Start(makecertPath, param);
18 p.WaitForExit();
19 p.Close();
20 }
21 catch (Exception e)
22 {
23 LogRecord.putErrorLog(e.ToString(), "DataCerficate.CreateCertWithPrivateKey");
24 return false;
25 }
26 return true;
27 }
28 #endregion
29
30 #region 文件导入导出
31 /// <summary>
32 /// 从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
33 /// 并导出为pfx文件,同时为其指定一个密码
34 /// 并将证书从个人区删除(如果isDelFromstor为true)
35 /// </summary>
36 /// <param name="subjectName">证书主题,不包含CN=</param>
37 /// <param name="pfxFileName">pfx文件名</param>
38 /// <param name="password">pfx文件密码</param>
39 /// <param name="isDelFromStore">是否从存储区删除</param>
40 /// <returns></returns>
41 public static bool ExportToPfxFile(string subjectName, string pfxFileName,
42 string password, bool isDelFromStore)
43 {
44 subjectName = "CN=" + subjectName;
45 X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
46 store.Open(OpenFlags.ReadWrite);
47 X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
48 foreach (X509Certificate2 x509 in storecollection)
49 {
50 if (x509.Subject == subjectName)
51 {
52 Debug.Print(string.Format("certificate name: {0}", x509.Subject));
53
54 byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);
55 using (FileStream fileStream = new FileStream(pfxFileName, FileMode.Create))
56 {
57 // Write the data to the file, byte by byte.
58 for (int i = 0; i < pfxByte.Length; i++)
59 fileStream.WriteByte(pfxByte[i]);
60 // Set the stream position to the beginning of the file.
61 fileStream.Seek(0, SeekOrigin.Begin);
62 // Read and verify the data.
63 for (int i = 0; i < fileStream.Length; i++)
64 {
65 if (pfxByte[i] != fileStream.ReadByte())
66 {
67 LogRecord.putErrorLog("Export pfx error while verify the pfx file!", "ExportToPfxFile");
68 fileStream.Close();
69 return false;
70 }
71 }
72 fileStream.Close();
73 }
74 if( isDelFromStore == true)
75 store.Remove(x509);
76 }
77 }
78 store.Close();
79 store = null;
80 storecollection = null;
81 return true;
82 }
83 /// <summary>
84 /// 从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
85 /// 并导出为CER文件(即,只含公钥的)
86 /// </summary>
87 /// <param name="subjectName"></param>
88 /// <param name="cerFileName"></param>
89 /// <returns></returns>
90 public static bool ExportToCerFile(string subjectName, string cerFileName)
91 {
92 subjectName = "CN=" + subjectName;
93 X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
94 store.Open(OpenFlags.ReadWrite);
95 X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
96 foreach (X509Certificate2 x509 in storecollection)
97 {
98 if (x509.Subject == subjectName)
99 {
100 Debug.Print(string.Format("certificate name: {0}", x509.Subject));
101 //byte[] pfxByte = x509.Export(X509ContentType.Pfx, password);
102 byte[] cerByte = x509.Export(X509ContentType.Cert);
103 using (FileStream fileStream = new FileStream(cerFileName, FileMode.Create))
104 {
105 // Write the data to the file, byte by byte.
106 for (int i = 0; i < cerByte.Length; i++)
107 fileStream.WriteByte(cerByte[i]);
108 // Set the stream position to the beginning of the file.
109 fileStream.Seek(0, SeekOrigin.Begin);
110 // Read and verify the data.
111 for (int i = 0; i < fileStream.Length; i++)
112 {
113 if (cerByte[i] != fileStream.ReadByte())
114 {
115 LogRecord.putErrorLog("Export CER error while verify the CERT file!", "ExportToCERFile");
116 fileStream.Close();
117 return false;
118 }
119 }
120 fileStream.Close();
121 }
122 }
123 }
124 store.Close();
125 store = null;
126 storecollection = null;
127 return true;
128 }
129 #endregion
130
131 #region 从证书中获取信息
132 /// <summary>
133 /// 根据私钥证书得到证书实体,得到实体后可以根据其公钥和私钥进行加解密
134 /// 加解密函数使用DEncrypt的RSACryption类
135 /// </summary>
136 /// <param name="pfxFileName"></param>
137 /// <param name="password"></param>
138 /// <returns></returns>
139 public static X509Certificate2 GetCertificateFromPfxFile(string pfxFileName,
140 string password)
141 {
142 try
143 {
144 return new X509Certificate2(pfxFileName, password, X509KeyStorageFlags.Exportable);
145 }
146 catch (Exception e)
147 {
148 LogRecord.putErrorLog("get certificate from pfx" + pfxFileName + " error:" + e.ToString(),
149 "GetCertificateFromPfxFile");
150 return null;
151 }
152 }
153 /// <summary>
154 /// 到存储区获取证书
155 /// </summary>
156 /// <param name="subjectName"></param>
157 /// <returns></returns>
158 public static X509Certificate2 GetCertificateFromStore(string subjectName)
159 {
160 subjectName = "CN=" + subjectName;
161 X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
162 store.Open(OpenFlags.ReadWrite);
163 X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
164 foreach (X509Certificate2 x509 in storecollection)
165 {
166 if (x509.Subject == subjectName)
167 {
168 return x509;
169 }
170 }
171 store.Close();
172 store = null;
173 storecollection = null;
174 return null;
175 }
176 /// <summary>
177 /// 根据公钥证书,返回证书实体
178 /// </summary>
179 /// <param name="cerPath"></param>
180 public static X509Certificate2 GetCertFromCerFile(string cerPath)
181 {
182 try
183 {
184 return new X509Certificate2(cerPath);
185 }
186 catch (Exception e)
187 {
188 LogRecord.putErrorLog(e.ToString(), "DataCertificate.LoadStudentPublicKey");
189 return null;
190 }
191 }
192 #endregion
193 }
194
转自:http://blog.csdn.net/luminji/archive/2009/03/05/3960308.aspx
转载于:https://www.cnblogs.com/NoRoad/archive/2010/03/01/1675866.html
(转)C#创建数字证书并导出为pfx,并使用pfx进行非对称加解密相关推荐
- 创建数字证书以及使用数字签名对UWP应用包签名
目录 创建数字签名 创建自签名证书 确定待打包应用的颁发者(Subject) 使用 New-SelfSignedCertificate 命令创建证书 导出证书 打包应用程序 使用SignTool进行签 ...
- 使用makecert.exe创建数字证书
不使用代码如何生成PFX和CER证书? 生成证书 查看并导出证书: 1.导出PFX证书 2.导出CER证书 生成证书 安装VS后makecert.exe即可使用,打开CMD后输入makecert,然后 ...
- java usbkey数字证书_Java创建数字证书
BouncyCastle下载: 链接:http://pan.baidu.com/s/1vrcL4 密码:6i27 package com.what21.security05; import ja ...
- C#数字证书编程总结
.NET中如何操作数字证书详解 http://blog.csdn.net/zjlovety/article/details/7252792 .NET为我们提供了操作数字证书的两个主要的类,分为为: S ...
- java pfx 和cer_数字证书文件格式(cer和pfx)的区别
作为文件形式存在的证书一般有这几种格式: 1.带有私钥的证书 由Public Key Cryptography Standards #12,PKCS#12标准定义,包含了公钥和私钥的二进制格式的证书形 ...
- 数字证书 - Java加密与安全
数字证书我们在前面看到了一些计算机密码学的一些算法1. 摘要算法确保数据没有被篡改2. 非对称加密就是对数据进行加解密3. 数据签名可以确保数据完整性和抗否认性而数字证书就是集合了多种密码学算法,用于 ...
- Excel 2010 VBA 入门 007 创建和使用数字证书签名
目录 操作方法 1.创建数字证书 步骤1 单击Windows中的"开始"按钮,在"所有程序"中找到Microsoft Office,在子文件夹"Mi ...
- 数字证书应用综合揭秘(包括证书生成、加密、解密、签名、验签)
引言 数字证书是一个经证书授权中心数字签名的包含公开密钥拥有者信息以及公开密钥的文件.为现实网络安全化标准如今大部分的 B2B.B2C.P2P.O2O 等商业网站含有重要企业资料个人资料的信息资信网站 ...
- 【上】安全HTTPS-全面详解对称加密,非对称加密,数字签名,数字证书和HTTPS
此文章转载来源于http://blog.csdn.net/tenfyguo/article/details/40922813点击打开链接 一,对称加密 所谓对称加密,就是它们在编码时使用的密钥e和解码 ...
最新文章
- 如何安装vscode网页版_Windows10专业版/企业版如何安装Microsoft store
- linuv创建文件的命令_ECS实践案例丨逻辑卷的创建和扩容操作指导
- axios请求接口http_使用axios请求接口,几种content-type的区别详解
- HDU-4604 Deque DP
- 管理系统中计算机应用 重点章节,11年《管理系统中计算机应用》 第5章 重点要点.doc...
- 计算机共享文件怎样添加,怎么添加另一台电脑的共享文件夹
- qt4--qt5引用头文件区别
- Ubuntu下映射串口设备到docker
- 企业内部应用对接钉钉 -- 钉钉回调
- Linux Vim 退出命令
- CentOS cp复制命令覆盖文件不提示 实现直接覆盖
- 凸集 凸函数 判定凸函数
- 手机服务器 微信QQ,玩家天价买服务器语聊开黑 小白没想明白:微信QQ难道不行?...
- 北航 计算机学院 加试两门,北航强军计划考研计算机学院招生.pdf
- 域控无法同步OUTLOOK提示“该姓名与地址列表中的的姓名不匹配”
- 几种开源图形相关的库的总结
- 深圳电子行业的mes系统的需求分析方法~先达智控
- 《初级会计电算化实用教程(金蝶KIS专业版)》一第1章 会计电算化概论
- 从面试到入职到离职,我在B站工作的30天时光!!!
- 玩大神的抖音小姐姐机器人遇到的问题
热门文章
- OpenGL 字体颜色问题
- [XA]转:一个关于结对编程(Pair Programming)的讲义
- Slog3_如何使用Python与Mysql进行数据交互
- 惠普发布软件定义存储 助力提升虚拟化能力
- 关于文章 Generating Impact-Based Summaries... By Mei qiaozhu
- 在win7下安装SQL sever2005
- CSS兼容性(IE和Firefox)技巧大全
- 冬天了,麦克风/话筒 有杂音 的原因!
- equals方法和==的区别--用实例简单说明
- 软件工程-东北师大站-第十二次作业(PSP)