简体   繁体   中英

How to add client certificate to Rest API in C#

如何基于以下 curl 将证书添加到 C# 中的 Rest API:

/drives/c/TempD/OpensslD curl --cacert <Server_CA_chain_file_name> --cert <Client_cert_file> --key <Client_key_file> -v -X POST --header 'Content-Type: application/json' --header 'Accept:application/json' -d '{"Info":{"functionRequesterIdentifier": "string","functionCallIdentifier":"string"},"profileType": " UMN_07.00"}' "https:/<Domain_Name>:12012/gsmak/rsp2/es/downloadOrder"

I think I've got it... This uses the BouncyCastle NuGet package.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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