简体   繁体   English

如何使用私钥获取证书的base 64编码值?

[英]How to get the base 64 encoded value of a certificate with private key?

Follow up to a previous question , I have some code that needs to get an X509 certificate with a private key. 按照上一个问题 ,我有一些代码需要获得带有私钥的X509证书。 As noted in the answers, in production this will happen using X509Store. 如答案中所述,在生产中,这将使用X509Store发生。

What is the best way to unit test this? 单元测试的最佳方法是什么? I want to develop and test with different certificates than will be in production, so I could create a CertificateRepository interface to provide different implementations. 我想使用不同于生产的证书来开发和测试,因此我可以创建一个CertificateRepository接口来提供不同的实现。

For the test / dev implementation, it would be nice to just use a base64 encoded string of the certificate, and create a cert instance that way, with a dummy password and dedicated test / dev cert. 对于测试/开发实现,最好只使用证书的base64编码字符串,并使用虚拟密码和专用测试/开发证书创建一个证书实例。 However so far I have been unable to figure out how to encode a certificate with private key as a base64 string. 但到目前为止,我一直无法弄清楚如何使用私钥作为base64字符串对证书进行编码。 Each time I try to export the cert from MMC as base-64, it encodes the public key only. 每次我尝试从MMC导出证书作为base-64时,它只对公钥进行编码。

I was unable to figure out how to do this with mmc. 我无法弄明白如何用mmc做到这一点。 However I did figure out how to do it in code: 但是我确实弄清楚如何在代码中执行此操作:

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, 
    "BLABLABLA", false)[0]; // doesn't matter how you get the cert
var exported = certificate.Export(X509ContentType.Pfx, "the password");
var base64 = Convert.ToBase64String(exported);
store.Close();

As long as the cert you are getting from the x 509 store has the private key, it will end up in the exported byte arrray, which you can then convert to a base64 string. 只要您从x 509商店获得的证书具有私钥,它将最终出现在导出的字节arrray中,然后您可以将其转换为base64字符串。

Make sure you mark private key as exportable when you add the certificate to the store. 将证书添加到商店时,请确保将私钥标记为可导出。

If you use makecert to create the certificate, add -pe option to make private key exportable. 如果使用makecert创建证书,请添加-pe选项以使私钥可导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM