X509从证书验证和创建Base64字符串
2016-10-25 23:27
423 查看
我手中的灯笼 使眼前黑暗的路途与我为敌
Program.cs代码:
class Program { static void Main(string[] args) { Console.WriteLine("X509证书实用程序"); Console.WriteLine("--------------------------"); Console.WriteLine(); Console.WriteLine("请输入证书(.cer)文件的路径: "); string location = Console.ReadLine(); if (location != null && File.Exists(location)) { ICertificateHelper certHelper = new CertificateHelper(); X509Certificate2 certificate = new X509Certificate2(location); Console.WriteLine("Encoded Base64 Value for Cert: "); Console.WriteLine(certHelper.CertificateBase64Value(certificate)); Console.WriteLine(certHelper.VerifyCertificate(certificate)); ConsoleKeyInfo key = Console.ReadKey(); } Console.WriteLine("完成."); } }
ICertificateHelper.cs代码:
public interface ICertificateHelper { bool VerifyCertificate(X509Certificate exportedCert); string CertificateBase64Value(X509Certificate certificate); }
CertificateHelper.cs代码:
public class CertificateHelper : ICertificateHelper { public bool VerifyCertificate(X509Certificate exportedCert) { string base64 = CertificateBase64Value(exportedCert); X509Certificate2 importCert = GetCertificateFromBase64(base64); return String.Equals(exportedCert.Subject, importCert.Subject); } private static X509Certificate2 GetCertificateFromBase64(string base64) { byte[] import = Encoding.Default.GetBytes(base64); return new X509Certificate2(import); } // 将证书保存为文件时,我们有三种选择: //带有私钥的证书 //由Public Key Cryptography Standards #12,PKCS#12标准定义,包含了公钥和私钥的二进制格式的证书形式,以pfx作为证书文件后缀名。 //二进制编码的证书 //证书中没有私钥,DER 编码二进制格式的证书文件,以cer作为证书文件后缀名。 //Base64编码的证书 //证书中没有私钥,BASE64 编码格式的证书文件,也是以cer作为证书文件后缀名。 public string CertificateBase64Value(X509Certificate certificate) { //证书导出到byte[]中,导出容器证书使用的是Export方法。 //第一个参数X509ContentType.Pfx表示要导出为含有私钥的pfx证书形式,第二个参数为私钥保护密码。 //如果要导出为不含私钥的cer证书,第一个参数使用X509ContentType.Cert,表示导出为不含私钥的cer证书,也就不需要密码了。 byte[] export = certificate.Export(X509ContentType.Cert); return Convert.ToBase64String(export); } }
相关文章推荐
- 创建X509证书,并获取证书密钥的一点研究
- 创建X509证书,并获取证书密钥的一点研究(转载)
- WCF使用X509证书身份验证
- OPENSSL X509证书验证
- X509证书验证研究(2)——GDB跟踪
- 创建X509证书,并获取证书密钥的一点研究
- x509证书验证示例
- WCF分布式安全开发实践(12):消息安全模式之自定义X509证书验证:Message_CustomX509Certificate_WSHttpBinding
- WCF分布式安全开发:消息安全模式之自定义X509证书验证
- OPENSSL X509证书验证
- WCF分布式安全开发实践(6):传输安全模式之自定义X509Certificate证书验证:Transport_X509Certificate_WSHttpBinding
- 创建X509证书,并获取证书密钥的一点研究
- 利用openssl验证X509证书是否是某CA签发
- OpenSSL证书创建、验证及加解密过程总结
- 如何为WCF应用添加X509证书和安全验证
- (转)创建X509证书,并获取证书密钥的一点研究
- WCF分布式安全开发实践(12):消息安全模式之自定义X509证书验证
- WCF身份验证之X509证书
- 【WCF安全】使用X509证书自定义验证
- android ssl双向验证 X509证书信任管理器类的实现及应用