c#通用应用平台证书公钥
本文关键字:证书 公钥 平台 应用 | 更新日期: 2023-09-27 17:53:37
在本文https://blogs.windows.com/buildingapps/2015/10/13/create-more-secure-apps-with-less-effort-10-by-10/中,他们向您解释了如何安全地连接到服务器。他们检查指纹以确认证书是合法的。但是证书会随着时间的推移而改变,我所检查的硬编码字符串将不再有效。
这就是我想提取公钥的原因。因为我确定它不会从一个证书改变到另一个。
在此代码中:
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;
}
在https://blogs.windows.com/buildingapps/2015/10/13/create-more-secure-apps-with-less-effort-10-by-10/#1tFDZeMtskOkOrvd.99阅读更多
很容易获取指纹。但我需要公钥。我在网上搜索,我发现了非常疯狂的代码,检查我不能使它工作。
有人能告诉我是否有一种简单的方法从Windows 10的证书中提取公钥?
问候。
x509证书。GetPublicKey方法适用于通用Windows平台。
你可以这样写:
var publicKey = certs[i].GetPublicKey();
或
byte[] publicKey = certs[i].GetPublicKey.EncodedKeyValue.RawData;
正如Tomas所说,有一个方法叫做GetPublicKey。它不包含在api中。刚注意到有个nuget包叫"System.Security.Cryptography "X509Certificates"
谢谢!