X509Certificate证书读取本地相应指纹证书

本文介绍了如何在C#控制台程序中使用X509Certificate2,包括配置类CertificateConfig的定义,以及CertificateManager类的实现,展示了如何获取证书并处理不同场景。
摘要由CSDN通过智能技术生成

X509Certificate证书所在的命名空间:

System.Security.Cryptography.X509Certificates

新建控制台程序 X509CertificateDemo,添加对System.Configuration的引用

一、新建配置类:CertificateConfig

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace X509CertificateDemo
{
    /// <summary>
    /// Certificate configuration
    /// </summary>
    public class CertificateConfig : ConfigurationElement
    {
        /// <summary>
        /// Gets the certificate file path.
        /// </summary>
        [ConfigurationProperty("filePath", IsRequired = false)]
        public string FilePath
        {
            get
            {
                return this["filePath"] as string;
            }
        }

        /// <summary>
        /// Gets the password.
        /// </summary>
        [ConfigurationProperty("password", IsRequired = false)]
        public string Password
        {
            get
            {
                return this["password"] as string;
            }
        }

        /// <summary>
        /// Gets the the store where certificate locates.
        /// </summary>
        /// <value>
        /// The name of the store.
        /// </value>
        [ConfigurationProperty("storeName", IsRequired = false)]
        public string StoreName
        {
            get
            {
                return this["storeName"] as string;
            }
        }

        /// <summary>
        /// Gets the store location of the certificate.
        /// </summary>
        /// <value>
        /// The store location.
        /// </value>
        [ConfigurationProperty("storeLocation", IsRequired = false, DefaultValue = "CurrentUser")]
        public StoreLocation StoreLocation
        {
            get
            {
                return (StoreLocation)this["storeLocation"];
            }
        }

        /// <summary>
        /// Gets the thumbprint.【指纹】
        /// </summary>
        [ConfigurationProperty("thumbprint", IsRequired = false)]
        public string Thumbprint
        {
            //get
            //{
            //    return this["thumbprint"] as string;
            //}
            get;set;
        }

        /// <summary>
        /// Gets a value indicating whether [client certificate required].
        /// </summary>
        /// <value>
        /// <c>true</c> if [client certificate required]; otherwise, <c>false</c>.
        /// </value>
        [ConfigurationProperty("clientCertificateRequired", IsRequired = false, DefaultValue = false)]
        public bool ClientCertificateRequired
        {
            get
            {
                return (bool)this["clientCertificateRequired"];
            }
        }

        /// <summary>
        /// Gets a value that will be used to instantiate the X509Certificate2 object in the CertificateManager
        /// </summary>
        [ConfigurationProperty("keyStorageFlags", IsRequired = false, DefaultValue = X509KeyStorageFlags.DefaultKeySet)]
        public X509KeyStorageFlags KeyStorageFlags
        {
            get
            {
                return (X509KeyStorageFlags)this["keyStorageFlags"];
            }
        }
    }
}
 

二、新建类CertificateManager,源程序如下:
 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;

namespace X509CertificateDemo
{
    /// <summary>
    /// 证书管理
    /// </summary>
    public class CertificateManager
    {
        public static X509Certificate GetCertificate(CertificateConfig certificate)
        {
            if (certificate == null)
            {
                Console.WriteLine("There is no certificate configured!");
                return null;
            }

            //文件路径 和 指纹 至少需要存在一个
            if (string.IsNullOrEmpty(certificate.FilePath) && string.IsNullOrEmpty(certificate.Thumbprint))
            {
                Console.WriteLine("You should define certificate node and either attribute 'filePath' or 'thumbprint' is required!");
                return null;
            }

            return Initialize(certificate, GetFilePath);
        }

        /// <summary>
        /// 如果应用程序根目录下存在该文件
        /// </summary>
        /// <param name="relativeFilePath"></param>
        /// <returns></returns>
        private static string GetFilePath(string relativeFilePath)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativeFilePath);
            if (!File.Exists(filePath))
            {
                string rootDir = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
                string rootFilePath = Path.Combine(rootDir, relativeFilePath);
                if (File.Exists(rootFilePath))
                    return rootFilePath;
            }
            return filePath;
        }

        private static X509Certificate Initialize(CertificateConfig certificateConfig, Func<string, string> relativePathHandler)
        {
            if (!string.IsNullOrEmpty(certificateConfig.FilePath))
            {
                //如果文件路径不为空
                string filePath = certificateConfig.FilePath;
                if (!Path.IsPathRooted(filePath))
                {
                    filePath = relativePathHandler(filePath);
                }
                return new X509Certificate2(filePath, certificateConfig.Password, certificateConfig.KeyStorageFlags);
            }
            else
            {
                //如果文件路径为空
                string storeName = certificateConfig.StoreName;
                if (string.IsNullOrEmpty(storeName))
                {
                    storeName = "Root";
                }
                X509Store store = new X509Store(storeName, certificateConfig.StoreLocation);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2 cert = store.Certificates.OfType<X509Certificate2>().Where(c => c.Thumbprint.Equals(certificateConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                store.Close();
                return cert;
            }
        }
    }
}
 

三、默认的控制台Program类,测试程序如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;

namespace X509CertificateDemo
{
    /// <summary>
    /// X509证书测试
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            X509Certificate certificate = CertificateManager.GetCertificate(new CertificateConfig() { Thumbprint = "A43489159A520F0D93D032CCAF37E7FE20A8B419" });
            if (certificate == null)
            {
                Console.WriteLine("没有找到该指纹对应的证书...");
                Console.ReadLine();
                return;
            }
            Console.WriteLine(certificate.ToString());
            Console.WriteLine("--------------------------------------");
            Console.WriteLine(certificate.ToString(true));
            Console.ReadLine();
        }
    }
}
 

四、运行效果如图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斯内科

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值