为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 UWP 应用中为 HTTPS 请求使用客户端证书

如何在 UWP 应用中为 HTTPS 请求使用客户端证书

C#
qq_遁去的一_1 2021-11-28 17:53:55
我正在编写一个应用程序,它需要发出一些使用客户端证书的 HTTPs 请求。但是,我找不到有关如何安装证书然后加载以使用的任何文档。我知道您可以通过制作HttpBaseProtocolFilter和添加证书来使用证书,但是您如何加载证书以供此处使用?如果您有一个带有客户端证书的 .pfx 文件,您如何将它与您的软件包一起安装?
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

对于它的价值,我最终使用 Portable.BouncyCastle NuGet 包和一些 UWP API 的组合来解决这个问题。我所做的一些示例(伪)代码如下:


// Asymmetric key pair

RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

keyPairGenerator.Init(

    new KeyGenerationParameters(

        new SecureRandom(new CryptoApiRandomGenerator()), 2048));

AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair();


// Create certificate

X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

generator.SetSubjectDN("foo");

generator.SetIssuerDN("foo");

generator.SetSerialNumber(new BigInteger("12345").Abs());

generator.SetNotBefore(DateTime.UtcNow);

generator.SetNotAfter(DateTime.UtcNow + TimeSpan.FromYears(1));

generator.SetPublicKey(keyPair.Public);


BouncyCastleX509Certificate certificate =

    generator.Generate(

        new Asn1SignatureFactory("SHA1WithRSA", keyPair.Private));


// Create PKCS12 certificate bytes.

Pkcs12Store store = new Pkcs12Store();

X509CertificateEntry certificateEntry = new X509CertificateEntry(certificate);

string friendlyName = "Friendly Name";

string password = "password";

store.SetCertificateEntry(friendlyName, certificateEntry);

store.SetKeyEntry(

    friendlyName,

    new AsymmetricKeyEntry(keyPair.Private),

    new X509CertificateEntry[] { certificateEntry });

string pfxData;

using (MemoryStream memoryStream = new MemoryStream(512))

{

    store.Save(memoryStream, password.ToCharArray(), this.SecureRandom);

    pfxData = CryptographicBuffer.EncodeToBase64String(memoryStream.ToArray().AsBuffer());

}


// Add the certificate to the cert store

await CertificateEnrollmentManager.ImportPfxDataAsync(

    pfxData,

    password,

    ExportOption.NotExportable,

    KeyProtectionLevel.NoConsent,

    InstallOptions.DeleteExpired,

    friendlyName);


// Read the UWP cert from the cert store

Certificate uwpCertificate =

    (await CertificateStores.FindAllAsync(

        new CertificateQuery { FriendlyName = friendlyName }))[0];


// Create the UWP HTTP client.

HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();

filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);

filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

filter.ClientCertificate = uwpCertificate;

HttpClient httpClient = new HttpClient(filter);


// Profit!



查看完整回答
反对 回复 2021-11-28
  • 1 回答
  • 0 关注
  • 244 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信