Fork me on GitHub

UWP 使用SSL证书,保证数据安全

事情是这样的,我们后端的小伙伴升级了用户会员系统,使用了全新的GraphQL登录机制,并且采用SSL加密的方式来实现阻止陌生客户端请求的案例。

GraphQL在UWP端的实现,以后有时间会单独写一篇文章,这里先说一下怎么在UWP里面使用SSL证书的问题。

 

其实接这个任务也是一个临时调研的,毕竟企业级SSL证书需要花钱买,而我们只是在内部先做一下,测试。

然后后端小伙伴给了一个测试的证书,并且导出了各种格式。

 

毕竟我对这个领域完全陌生,就像前面提到的那个GraphQL一样,蒙圈的那种。

但是工作还是要继续的,于是Google一顿猛于虎的搜索🔍,终于找到了一些指引。

1. 添加Capabilities

 勾选 Shared User Certificates

 

 

2. 添加Declarations

Available Declarations里面选择Certificates,然后点击Add即可。

这一步需要注意,网上有的教程说需要勾选 Exclusive trust。还要在最底下Certificates,点击Add New,设置Store name以及Content。

看你需要吧,我没做。也不懂这是干嘛的。😳

 

 

 

3. 添加SSL证书文件

 右击解决方案,选择你的SSL证书,并且把Build Action改为Content

UWP里面我尝试了pfx和p12格式的,均可以正常使用。

其他的证书格式未验证。

 

 

4. 添加HttpClient代码

 

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
//Wrong method to import cert
//StorageFile certificateFile = await Package.Current.InstalledLocation.GetFileAsync(@"client.p12"); //IBuffer certificateBuffer = await FileIO.ReadBufferAsync(certificateFile); //string encodedCertificate = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(certificateBuffer); //await CertificateEnrollmentManager.ImportPfxDataAsync(encodedCertificate, "000000", ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "Client Certificate");
//Better use it this way. Add cert to HttpClientHandler var handler = new HttpClientHandler(); handler.ClientCertificateOptions = ClientCertificateOption.Manual; X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes("client.pfx"), "000000"); handler.ClientCertificates.Add(cer); HttpClient client = new HttpClient(handler); HttpResponseMessage response = await client.GetAsync("https://test.client.ssl/"); //HttpResponseMessage response = await client.GetAsync("https://192.168.101.99/"); response.EnsureSuccessStatusCode(); string temp = await response.Content.ReadAsStringAsync(); }

然后别忘了添加引用

using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

 

 

 5. Done!!!

如果成功访问指定的ip,并且获取到了数据的话,那么说明完成了。

posted @ 2019-12-19 15:31  猫叔Vincent  阅读(567)  评论(0编辑  收藏  举报