为证书提供EC私钥以在HttpClient C#中使用

时间:2019-02-14 11:28:15

标签: c# ssl

我有一个可以使用X509Certificate2类读取的证书:

X509Certificate2证书=新的X509Certificate2(@“ certificate.pem”);

但是我还有一个 EC 私钥。这是文件的内容。

X509Certificate2 certificate = new X509Certificate2(@"certificate.pem");
//certificate.PrivateKey = something;
httpClientHandler.ClientCertificates.Clear();
httpClientHandler.ClientCertificates.Add(certificate);
httpClientHandler.SslProtocols = SslProtocols.Tls12;
httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;

HttpClient httpClient = new HttpClient(httpClientHandler);
HttpResponseMessage result = httpClient.GetAsync("https://server.cryptomix.com/secure/").Result;
string str = result.Content.ReadAsStringAsync().Result;

如何将此私钥“馈送”给证书,并最终“馈给”我的 HttpClient ,以便它可以用作客户端证书?

这是我其余的代码:

        function _cloneWithSeq (list) {
            return _.map(ko.unwrap(list), function (item) {
                var cloneItem = _.clone(item);
                cloneItem.seq = ko.observable(ko.unwrap(item.seq));
                return cloneItem;
            });
        }

2 个答案:

答案 0 :(得分:2)

我想我已经明白了...它使用了BouncyCastle NuGet软件包。

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using System.Security.Cryptography.X509Certificates;
using System;
using System.IO;

string pemKey = @"-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIKpAuZ/Wwp7FTSCNJ56fFM4Y/rf8ltXp3xnrooPxNc1UoAoGCCqGSM49
AwEHoUQDQgAEqiRaEw3ItPsRAqdDjJCyqxhfm8y3tVrxLBAGhPM0pVhHuqmPoQFA
zR5FA3IJZaWcopieEX5uZ4KMtDhLFu/FHw==
-----END EC PRIVATE KEY-----";

string pemCert = @"-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----";

var keyPair = (AsymmetricCipherKeyPair)new PemReader(new StringReader(pemKey)).ReadObject();
var cert = (Org.BouncyCastle.X509.X509Certificate)new PemReader(new StringReader(pemCert)).ReadObject();

var builder = new Pkcs12StoreBuilder();
builder.SetUseDerEncoding(true);
var store = builder.Build();

var certEntry = new X509CertificateEntry(cert);
store.SetCertificateEntry("", certEntry);
store.SetKeyEntry("", new AsymmetricKeyEntry(keyPair.Private), new[] { certEntry });

byte[] data;
using (var ms = new MemoryStream())
{
    store.Save(ms, Array.Empty<char>(), new SecureRandom());
    data = ms.ToArray();
}

var x509Cert = new X509Certificate2(data);

诀窍似乎是将证书和密钥组合到一个pkcs12容器中,然后一次性将其馈送到X509Certificate2中。

答案 1 :(得分:0)

将证书和密钥与openssl结合在一起,并将其馈送到x509certificate类中是可行的:

openssl pkcs12 -export -in certificate.pem -inkey privatekey.pem -out cert-and-key.pfx

然后使用它来获取具有分配的私钥的类:

X509Certificate2 certificate = new X509Certificate2("cert-and-key.pfx", "password");

然后我问题中的代码起作用。