在UWP中导入服务器证书(+链)的正确方法



我正在尝试导入服务器的证书,随后我将连接该证书。

  1. 我的第一个障碍是导入证书的正确方法是什么在UWP中,[注意:包装.pfx违反了商店政策]
  2. 导入服务器证书后,如何导入/获取签署服务器证书的根CA的证书

我目前正在使用以下代码,但我仍然有以上问题?

public async Task InsertCert()
{
StorageFile pfxfile = await ApplicationData.Current.LocalFolder.GetFileAsync("ms-appx:///myfile.pfx");
var buffer = await FileIO.ReadBufferAsync(pfxfile);
string certificateData = CryptographicBuffer.EncodeToBase64String(buffer);
string password = "";
await CertificateEnrollmentManager.ImportPfxDataAsync(
certificateData,
password,
ExportOption.NotExportable,
KeyProtectionLevel.NoConsent,
InstallOptions.None,
"Client Certificate");
}

我检查了您的代码,但有些地方我不理解。

例如,您使用此行代码获取本地文件夹中的".pfx"文件。

StorageFile pfxfile=await ApplicationData.Current.LocalFolder.GetFileAsync("ms-appx:///myfile.pfx"(;

ms-appx:///是您的应用程序包。ApplicationData.Current.LocalFolder是您的应用程序数据文件夹,它等于ms-appdata:///local/。它们是不同的东西。

在您的情况下,如果".pfx"文件在本地文件夹的根目录中,您可以直接使用await ApplicationData.Current.LocalFolder.GetFileAsync("myfile.pfx")来获取它。

然后,让我们回到您的"导入/获取证书"问题。我看到您正在使用CertificateEnrollmentManager.ImportPfxDataAsync在应用程序容器存储中安装".pfx"证书。这是正确的。

成功安装证书后,可以通过调用Windows.Security.Cryptography.Certificates.CertificateStores.FindAllAsync(certQuery)获取证书。

根据您在ImportPfxDataAsync方法中指定的FriendlyName,您可以创建CertificateQuery作为CertificateStores.FindAllAsync方法参数。

Windows.Security.Cryptography.Certificates.CertificateQuery certQuery = new Windows.Security.Cryptography.Certificates.CertificateQuery();
certQuery.FriendlyName = "Client Certificate";    // This is the friendly name of the certificate that was just installed.
IReadOnlyList<Windows.Security.Cryptography.Certificates.Certificate> certs = await Windows.Security.Cryptography.Certificates.CertificateStores.FindAllAsync(certQuery);
foreach (Certificate cert in certs)
{
Debug.WriteLine($"FriendlyName: {cert.FriendlyName},Subject: {cert.Subject}, Serial Number: {CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(cert.SerialNumber))}");
}

一旦找到证书,就可以使用它与服务器进行通信。

例如,

您可以使用Windows.Web.Http.HttpClient类以编程方式附加已安装的客户端证书。

Windows.Web.Http.Filters.HttpBaseProtocolFilter filter= new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.ClientCertificate = [your certificate];
Windows.Web.Http.HttpClient Client = new Windows.Web.Http.HttpClient(filter);
await Client.GetAsync(...);

最新更新