您的位置:首页 > 其它

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: