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();
}
}
}
四、运行效果如图: