C#通用应用程序平台中证书的公钥

C#通用应用程序平台中证书的公钥,c#,certificate,win-universal-app,ssl-certificate,C#,Certificate,Win Universal App,Ssl Certificate,在本文中,它们将解释如何安全地连接到服务器。他们检查指纹,看证书是否合法。但是证书会随着时间的推移而改变,我检查的硬编码字符串将不再有效 这就是我想提取公钥的原因。因为我确信它不会从一个证书变为另一个 在此代码中: private async Task DemoSSLRoot() { // Send a get request to Bing HttpClient client = new HttpClient(); Uri

在本文中,它们将解释如何安全地连接到服务器。他们检查指纹,看证书是否合法。但是证书会随着时间的推移而改变,我检查的硬编码字符串将不再有效

这就是我想提取公钥的原因。因为我确信它不会从一个证书变为另一个

在此代码中:

        private async Task DemoSSLRoot()
    {
        // Send a get request to Bing
        HttpClient client = new HttpClient();
        Uri bingUri = new Uri("https://www.bing.com");
        HttpResponseMessage response = await client.GetAsync(bingUri);

        // Get the list of certificates that were used to validate the server's identity
        IReadOnlyList<Certificate> serverCertificates = response.RequestMessage.TransportInformation.ServerIntermediateCertificates;

        // Perform validation
        if (!ValidCertificates(serverCertificates))
        {
            // Close connection as chain is not valid
            return;
        }

        PrintResults("Validation passed\n");
        // Validation passed, continue with connection to service
    }

    private bool ValidCertificates(IReadOnlyList<Certificate> certs)
    {
        // In this example, we iterate through the certificates and check that the chain contains
        // one specific certificate we are expecting
        for (int i = 0; i < certs.Count; i++)
        {
            PrintResults("Cert# " + i + ": " + certs[i].Subject + "\n");
            byte[] thumbprint = certs[i].GetHashValue();

            // Check if the thumbprint matches whatever you are expecting
            // ‎d4 de 20 d0 5e 66 fc 53 fe 1a 50 88 2c 78 db 28 52 ca e4 74
            byte[] expected = new byte[] { 212, 222, 32, 208, 94, 102, 252, 83, 254, 26, 80, 136, 44, 120, 219, 40, 82, 202, 228, 116 };

            if (ThumbprintMatches(thumbprint, expected))
            {
                return true;
            }
        }

        return false;
    }
private异步任务DemoSSLRoot()
{
//向Bing发送get请求
HttpClient=新的HttpClient();
Uri bingUri=新Uri(“https://www.bing.com");
HttpResponseMessage response=wait client.GetAsync(bingUri);
//获取用于验证服务器身份的证书列表
IReadOnlyList serverCertificates=response.RequestMessage.TransportInformation.ServerIntermediateCertificates;
//执行验证
如果(!有效证书(服务器证书))
{
//关闭连接,因为链无效
返回;
}
打印结果(“验证通过\n”);
//验证通过,继续连接到服务
}
私人bool有效证书(IReadOnlyList证书)
{
//在本例中,我们遍历证书并检查链是否包含
//我们期待一份具体的证书
对于(int i=0;i
阅读更多

很容易找到指纹。但我需要公钥。 我在互联网上搜索,我发现了非常疯狂的代码来检查我是否能让它工作

有人能告诉我在Windows10中是否有一种简单的方法可以从证书中提取公钥吗


注意。

X509Certificate.GetPublicKey方法可用于通用Windows平台

例如,您可以使用:

var publicKey = certs[i].GetPublicKey();


正如Tomas所说,有一种方法叫做GetPublicKey。它不包括在API中。刚刚注意到有一个名为“System.Security.Cryptography.X509Certificates”的nuget包,其中提供了此方法


谢谢

GetPublicKey不适用于windows通用应用程序,尽管它存在于我不知道的命名空间中?
byte[] publicKey = certs[i].GetPublicKey.EncodedKeyValue.RawData;