亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 274 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號