X509从证书验证和创建Base64字符串

我手中的灯笼 使眼前黑暗的路途与我为敌


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);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值