cer
HTTP://blog.csdn.net/zj510/article/details/39964533
PKI技术(public key infrastructure)里面,cer文件和pfx文件是很常见的。通常cer文件里面保存着公钥以及用户的一些信息,pfx里面则含有私钥和公钥。
用makecert.exe可以创建公钥证书和私钥证书,具体看
http://msdn.microsoft.com/zh-cn/library/bfsktky3(v=vs.110).aspx
http://blog.csdn.net/hacode/article/details/4240238
这里使用程序的方法来创建。参考了http://www.cnblogs.com/luminji/archive/2010/10/28/1863179.HTML
下面的代码封装了一个类,可以在store里面创建一个认证,并且导出到cer,pfx,然后从store,cer,pfx读取信息
[csharp]view plaincopy
- publicsealedclassDataCertificate
- {
- #region生成证书
- ///<summary>
- ///根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区)
- ///</summary>
- ///<paramname="subjectName"></param>
- ///<paramname="makecertPath"></param>
- ///<returns></returns>
- publicstaticboolCreateCertwithPrivateKey(stringsubjectName,stringmakecertPath)
- {
- subjectName="CN="+subjectName;
- stringparam="-pe-ssmy-n\""+subjectName+"\"";
- try
- {
- Processp=Process.Start(makecertPath,param);
- p.waitforExit();
- p.Close();
- }
- catch(Exceptione)
- {
- returnfalse;
- }
- returntrue;
- }
- #endregion
- #region文件导入导出
- ///<summary>
- ///从windows证书存储区的个人MY区找到主题为subjectName的证书,
- ///并导出为pfx文件,同时为其指定一个密码
- ///并将证书从个人区删除(如果isDelFromstor为true)
- ///</summary>
- ///<paramname="subjectName">证书主题,不包含CN=</param>
- ///<paramname="pfxFileName">pfx文件名</param>
- ///<paramname="password">pfx文件密码</param>
- ///<paramname="isDelFromStore">是否从存储区删除</param>
- ///<returns></returns>
- publicstaticboolExportToPfxFile(stringsubjectName,stringpfxFileName,
- stringpassword,boolisDelFromStore)
- {
- subjectName="CN="+subjectName;
- X509Storestore=newX509Store(StoreName.My,StoreLocation.CurrentUser);
- store.Open(OpenFlags.ReadWrite);
- X509Certificate2Collectionstorecollection=(X509Certificate2Collection)store.Certificates;
- foreach(X509Certificate2x509instorecollection)
- {
- if(x509.Subject==subjectName)
- {
- Debug.print(string.format("certificatename:{0}",x509.Subject));
- byte[]pfxByte=x509.Export(X509contentType.Pfx,password);
- using(filestreamfileStream=newFileStream(pfxFileName,FileMode.Create))
- {
- //Writethedatatothefile,bytebybyte.
- for(inti=0;i<pfxByte.Length;i++)
- fileStream.WriteByte(pfxByte[i]);
- //Setthestreampositiontothebeginningofthefile.
- fileStream.Seek(0,SeekOrigin.Begin);
- //Readandverifythedata.
- for(inti=0;i<fileStream.Length;i++)
- {
- if(pfxByte[i]!=fileStream.ReadByte())
- {
- fileStream.Close();
- returnfalse;
- }
- }
- fileStream.Close();
- }
- if(isDelFromStore==true)
- store.Remove(x509);
- }
- }
- store.Close();
- store=null;
- storecollection=null;
- returntrue;
- }
- ///<summary>
- ///从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
- ///并导出为CER文件(即,只含公钥的)
- ///</summary>
- ///<paramname="subjectName"></param>
- ///<paramname="cerFileName"></param>
- ///<returns></returns>
- publicstaticboolExportToCerFile(stringsubjectName,stringcerFileName)
- {
- subjectName="CN="+subjectName;
- X509Storestore=newX509Store(StoreName.My,StoreLocation.CurrentUser);
- store.Open(OpenFlags.ReadWrite);
- X509Certificate2Collectionstorecollection=(X509Certificate2Collection)store.Certificates;
- foreach(X509Certificate2x509instorecollection)
- {
- if(x509.Subject==subjectName)
- {
- Debug.Print(string.Format("certificatename:{0}",x509.Subject));
- //byte[]pfxByte=x509.Export(X509ContentType.Pfx,password);
- byte[]cerByte=x509.Export(X509ContentType.Cert);
- using(FileStreamfileStream=newFileStream(cerFileName,FileMode.Create))
- {
- //Writethedatatothefile,bytebybyte.
- for(inti=0;i<cerByte.Length;i++)
- fileStream.WriteByte(cerByte[i]);
- //Setthestreampositiontothebeginningofthefile.
- fileStream.Seek(0,SeekOrigin.Begin);
- //Readandverifythedata.
- for(inti=0;i<fileStream.Length;i++)
- {
- if(cerByte[i]!=fileStream.ReadByte())
- {
- fileStream.Close();
- returnfalse;
- }
- }
- fileStream.Close();
- }
- }
- }
- store.Close();
- store=null;
- storecollection=null;
- returntrue;
- }
- #endregion
- #region从证书中获取信息
- ///<summary>
- ///根据私钥证书得到证书实体,得到实体后可以根据其公钥和私钥进行加解密
- ///加解密函数使用DEncrypt的RSACryption类
- ///</summary>
- ///<paramname="pfxFileName"></param>
- ///<paramname="password"></param>
- ///<returns></returns>
- publicstaticX509Certificate2GetCertificateFromPfxFile(stringpfxFileName,
- stringpassword)
- {
- try
- {
- returnnewX509Certificate2(pfxFileName,password,X509KeyStorageFlags.Exportable);
- }
- catch(Exceptione)
- {
- returnnull;
- }
- }
- ///<summary>
- ///到存储区获取证书
- ///</summary>
- ///<paramname="subjectName"></param>
- ///<returns></returns>
- publicstaticX509Certificate2GetCertificateFromStore(stringsubjectName)
- {
- subjectName="CN="+subjectName;
- X509Storestore=newX509Store(StoreName.My,StoreLocation.CurrentUser);
- store.Open(OpenFlags.ReadWrite);
- X509Certificate2Collectionstorecollection=(X509Certificate2Collection)store.Certificates;
- foreach(X509Certificate2x509instorecollection)
- {
- if(x509.Subject==subjectName)
- {
- returnx509;
- }
- }
- store.Close();
- store=null;
- storecollection=null;
- returnnull;
- }
- ///<summary>
- ///根据公钥证书,返回证书实体
- ///</summary>
- ///<paramname="cerPath"></param>
- publicstaticX509Certificate2GetCertFromCerFile(stringcerPath)
- {
- try
- {
- returnnewX509Certificate2(cerPath);
- }
- catch(Exceptione)
- {
- returnnull;
- }
- }
- #endregion
- }
两个RSA加解密辅助函数:
[csharp]view plaincopy
- staticstringRSADecrypt(stringxmlPrivateKey,stringm_strDecryptString)
- {
- RSACryptoServiceProviderprovider=newRSACryptoServiceProvider();
- provider.FromXmlString(xmlPrivateKey);
- byte[]rgb=Convert.Frombase64String(m_strDecryptString);
- byte[]bytes=provider.Decrypt(rgb,false);
- returnnewunicodeEncoding().GetString(bytes);
- }
- ///<summary>
- ///RSA加密
- ///</summary>
- ///<paramname="xmlPublicKey"></param>
- ///<paramname="m_strEncryptString"></param>
- ///<returns></returns>
- staticstringRSAEncrypt(stringxmlPublicKey,stringm_strEncryptString)
- {
- RSACryptoServiceProviderprovider=newRSACryptoServiceProvider();
- provider.FromXmlString(xmlPublicKey);
- byte[]bytes=newUnicodeEncoding().GetBytes(m_strEncryptString);
- returnConvert.ToBase64String(provider.Encrypt(bytes,false));
- }
使用例子,下面的代码做了几个事情
1. 在个人store里面创建了一个认证, 从认证里面读取信息得到一个X509Certificate2的对象,这个对象内部包含公钥和私钥,然后做了次rsa加解密测试。
2. 从store里面导出一个cer文件,因为cer文件并没有私钥,只有公钥。测试代码就是用公钥加密然后用前面得到的私钥解密。
3. 导出一个pfx文件,pfx包括公钥和私钥,可以自己加解密。
这是个很简单的例子,但是对于理解cer文件和pfx文件已经公钥私钥应该有帮助。
[csharp]view plaincopy
- //在personal(个人)里面创建一个foo的证书
- DataCertificate.CreateCertWithPrivateKey("foo","C:\\ProgramFiles(x86)\\WindowsKits\\8.1\\bin\\x64\\makecert.exe");
- //获取证书
- X509Certificate2c1=DataCertificate.GetCertificateFromStore("foo");
- stringkeyPublic=c1.PublicKey.Key.ToXmlString(false);//公钥
- stringkeyPrivate=c1.PrivateKey.ToXmlString(true);//私钥
- stringcypher=RSAEncrypt(keyPublic,"程序员");//加密
- stringplain=RSADecrypt(keyPrivate,cypher);//解密
- Debug.Assert(plain=="程序员");
- //生成一个cert文件
- DataCertificate.ExportToCerFile("foo","d:\\mycert\\foo.cer");
- X509Certificate2c2=DataCertificate.GetCertFromCerFile("d:\\mycert\\foo.cer");
- stringkeyPublic2=c2.PublicKey.Key.ToXmlString(false);
- boolb=keyPublic2==keyPublic;
- stringcypher2=RSAEncrypt(keyPublic2,"程序员2");//加密
- stringplain2=RSADecrypt(keyPrivate,cypher2);//解密,cer里面并没有私钥,所以这里使用前面得到的私钥来解密
- Debug.Assert(plain2=="程序员2");
- //生成一个pfx,并且从store里面删除
- DataCertificate.ExportToPfxFile("foo","d:\\mycert\\foo.pfx","111",true);
- X509Certificate2c3=DataCertificate.GetCertificateFromPfxFile("d:\\mycert\\foo.pfx","111");
- stringkeyPublic3=c3.PublicKey.Key.ToXmlString(false);//公钥
- stringkeyPrivate3=c3.PrivateKey.ToXmlString(true);//私钥
- stringcypher3=RSAEncrypt(keyPublic3,"程序员3");//加密
- stringplain3=RSADecrypt(keyPrivate3,cypher3);//解密
- Debug.Assert(plain3=="程序员3");
附:完整代码
[csharp]view plaincopy
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.Diagnostics;
- usingSystem.IO;
- usingSystem.Linq;
- usingSystem.Security.Cryptography;
- usingSystem.Security.Cryptography.X509Certificates;
- usingSystem.Text;
- namespaceconsoleAPPlication1
- {
- publicsealedclassDataCertificate
- {
- #region生成证书
- ///<summary>
- ///根据指定的证书名和makecert全路径生成证书(包含公钥和私钥,并保存在MY存储区)
- ///</summary>
- ///<paramname="subjectName"></param>
- ///<paramname="makecertPath"></param>
- ///<returns></returns>
- publicstaticboolCreateCertWithPrivateKey(stringsubjectName,stringmakecertPath)
- {
- subjectName="CN="+subjectName;
- stringparam="-pe-ssmy-n\""+subjectName+"\"";
- try
- {
- Processp=Process.Start(makecertPath,param);
- p.WaitForExit();
- p.Close();
- }
- catch(Exceptione)
- {
- returnfalse;
- }
- returntrue;
- }
- #endregion
- #region文件导入导出
- ///<summary>
- ///从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
- ///并导出为pfx文件,同时为其指定一个密码
- ///并将证书从个人区删除(如果isDelFromstor为true)
- ///</summary>
- ///<paramname="subjectName">证书主题,不包含CN=</param>
- ///<paramname="pfxFileName">pfx文件名</param>
- ///<paramname="password">pfx文件密码</param>
- ///<paramname="isDelFromStore">是否从存储区删除</param>
- ///<returns></returns>
- publicstaticboolExportToPfxFile(stringsubjectName,stringpfxFileName,
- stringpassword,boolisDelFromStore)
- {
- subjectName="CN="+subjectName;
- X509Storestore=newX509Store(StoreName.My,StoreLocation.CurrentUser);
- store.Open(OpenFlags.ReadWrite);
- X509Certificate2Collectionstorecollection=(X509Certificate2Collection)store.Certificates;
- foreach(X509Certificate2x509instorecollection)
- {
- if(x509.Subject==subjectName)
- {
- Debug.Print(string.Format("certificatename:{0}",x509.Subject));
- byte[]pfxByte=x509.Export(X509ContentType.Pfx,password);
- using(FileStreamfileStream=newFileStream(pfxFileName,FileMode.Create))
- {
- //Writethedatatothefile,bytebybyte.
- for(inti=0;i<pfxByte.Length;i++)
- fileStream.WriteByte(pfxByte[i]);
- //Setthestreampositiontothebeginningofthefile.
- fileStream.Seek(0,SeekOrigin.Begin);
- //Readandverifythedata.
- for(inti=0;i<fileStream.Length;i++)
- {
- if(pfxByte[i]!=fileStream.ReadByte())
- {
- fileStream.Close();
- returnfalse;
- }
- }
- fileStream.Close();
- }
- if(isDelFromStore==true)
- store.Remove(x509);
- }
- }
- store.Close();
- store=null;
- storecollection=null;
- returntrue;
- }
- ///<summary>
- ///从WINDOWS证书存储区的个人MY区找到主题为subjectName的证书,
- ///并导出为CER文件(即,只含公钥的)
- ///</summary>
- ///<paramname="subjectName"></param>
- ///<paramname="cerFileName"></param>
- ///<returns></returns>
- publicstaticboolExportToCerFile(stringsubjectName,stringcerFileName)
- {
- subjectName="CN="+subjectName;
- X509Storestore=newX509Store(StoreName.My,StoreLocation.CurrentUser);
- store.Open(OpenFlags.ReadWrite);
- X509Certificate2Collectionstorecollection=(X509Certificate2Collection)store.Certificates;
- foreach(X509Certificate2x509instorecollection)
- {
- if(x509.Subject==subjectName)
- {
- Debug.Print(string.Format("certificatename:{0}",x509.Subject));
- //byte[]pfxByte=x509.Export(X509ContentType.Pfx,password);
- byte[]cerByte=x509.Export(X509ContentType.Cert);
- using(FileStreamfileStream=newFileStream(cerFileName,FileMode.Create))
- {
- //Writethedatatothefile,bytebybyte.
- for(inti=0;i<cerByte.Length;i++)
- fileStream.WriteByte(cerByte[i]);
- //Setthestreampositiontothebeginningofthefile.
- fileStream.Seek(0,SeekOrigin.Begin);
- //Readandverifythedata.
- for(inti=0;i<fileStream.Length;i++)
- {
- if(cerByte[i]!=fileStream.ReadByte())
- {
- fileStream.Close();
- returnfalse;
- }
- }
- fileStream.Close();
- }
- }
- }
- store.Close();
- store=null;
- storecollection=null;
- returntrue;
- }
- #endregion
- #region从证书中获取信息
- ///<summary>
- ///根据私钥证书得到证书实体,得到实体后可以根据其公钥和私钥进行加解密
- ///加解密函数使用DEncrypt的RSACryption类
- ///</summary>
- ///<paramname="pfxFileName"></param>
- ///<paramname="password"></param>
- ///<returns></returns>
- publicstaticX509Certificate2GetCertificateFromPfxFile(stringpfxFileName,
- stringpassword)
- {
- try
- {
- returnnewX509Certificate2(pfxFileName,password,X509KeyStorageFlags.Exportable);
- }
- catch(Exceptione)
- {
- returnnull;
- }
- }
- ///<summary>
- ///到存储区获取证书
- ///</summary>
- ///<paramname="subjectName"></param>
- ///<returns></returns>
- publicstaticX509Certificate2GetCertificateFromStore(stringsubjectName)
- {
- subjectName="CN="+subjectName;
- X509Storestore=newX509Store(StoreName.My,StoreLocation.CurrentUser);
- store.Open(OpenFlags.ReadWrite);
- X509Certificate2Collectionstorecollection=(X509Certificate2Collection)store.Certificates;
- foreach(X509Certificate2x509instorecollection)
- {
- if(x509.Subject==subjectName)
- {
- returnx509;
- }
- }
- store.Close();
- store=null;
- storecollection=null;
- returnnull;
- }
- ///<summary>
- ///根据公钥证书,返回证书实体
- ///</summary>
- ///<paramname="cerPath"></param>
- publicstaticX509Certificate2GetCertFromCerFile(stringcerPath)
- {
- try
- {
- returnnewX509Certificate2(cerPath);
- }
- catch(Exceptione)
- {
- returnnull;
- }
- }
- #endregion
- }
- classProgram
- {
- staticstringRSADecrypt(stringxmlPrivateKey,stringm_strDecryptString)
- {
- RSACryptoServiceProviderprovider=newRSACryptoServiceProvider();
- provider.FromXmlString(xmlPrivateKey);
- byte[]rgb=Convert.FromBase64String(m_strDecryptString);
- byte[]bytes=provider.Decrypt(rgb,false);
- returnnewUnicodeEncoding().GetString(bytes);
- }
- ///<summary>
- ///RSA加密
- ///</summary>
- ///<paramname="xmlPublicKey"></param>
- ///<paramname="m_strEncryptString"></param>
- ///<returns></returns>
- staticstringRSAEncrypt(stringxmlPublicKey,stringm_strEncryptString)
- {
- RSACryptoServiceProviderprovider=newRSACryptoServiceProvider();
- provider.FromXmlString(xmlPublicKey);
- byte[]bytes=newUnicodeEncoding().GetBytes(m_strEncryptString);
- returnConvert.ToBase64String(provider.Encrypt(bytes,false));
- }
- staticvoidMain(string[]args)
- {
- //在personal(个人)里面创建一个foo的证书
- DataCertificate.CreateCertWithPrivateKey("foo","C:\\ProgramFiles(x86)\\WindowsKits\\8.1\\bin\\x64\\makecert.exe");
- //获取证书
- X509Certificate2c1=DataCertificate.GetCertificateFromStore("foo");
- stringkeyPublic=c1.PublicKey.Key.ToXmlString(false);//公钥
- stringkeyPrivate=c1.PrivateKey.ToXmlString(true);//私钥
- stringcypher=RSAEncrypt(keyPublic,"程序员");//加密
- stringplain=RSADecrypt(keyPrivate,cypher);//解密
- Debug.Assert(plain=="程序员");
- //生成一个cert文件
- DataCertificate.ExportToCerFile("foo","d:\\mycert\\foo.cer");
- X509Certificate2c2=DataCertificate.GetCertFromCerFile("d:\\mycert\\foo.cer");
- stringkeyPublic2=c2.PublicKey.Key.ToXmlString(false);
- boolb=keyPublic2==keyPublic;
- stringcypher2=RSAEncrypt(keyPublic2,"程序员2");//加密
- stringplain2=RSADecrypt(keyPrivate,cypher2);//解密,cer里面并没有私钥,所以这里使用前面得到的私钥来解密
- Debug.Assert(plain2=="程序员2");
- //生成一个pfx,并且从store里面删除
- DataCertificate.ExportToPfxFile("foo","d:\\mycert\\foo.pfx","111",true);
- X509Certificate2c3=DataCertificate.GetCertificateFromPfxFile("d:\\mycert\\foo.pfx","111");
- stringkeyPublic3=c3.PublicKey.Key.ToXmlString(false);//公钥
- stringkeyPrivate3=c3.PrivateKey.ToXmlString(true);//私钥
- stringcypher3=RSAEncrypt(keyPublic3,"程序员3");//加密
- stringplain3=RSADecrypt(keyPrivate3,cypher3);//解密
- Debug.Assert(plain3=="程序员3");
- }
- }
- }
相关阅读
1 traceroute 功能说明:显示数据包到主机间的路径。它默认发送的数据包大小是40字节。 通过traceroute我们可以知道信息从你的计
Packet Tracer 思科模拟器入门教程 之一 初识Packet T
Packet Tracer介绍 Packet Tracer是Cisco公司针对CCNA认证开发的一个用来设计、配置和故障排除网络的模拟软件。 Packer Tracer
本本从2012-12-25购买到现在快3年了,期间把内存增加到8G,硬盘升级为1T的,一直任劳任怨得为我工作着,最近感觉散热不是很好,决定拆
谷歌日前正加快速度完成一项关于mkcert的开源项目,项目本身允许开发者在本地部署https测试环境,而mkcert是一个能够让网站通过自动
笔记本电脑的内存和电脑的操作体验有很大的关系,往往换更大的内存电脑会更流畅,可以开启的任务也更多,这篇和大家分享如何给宏碁acer