如何在c#中检索证书信息用于客户端身份验证
本文关键字:信息 用于 客户端 身份验证 证书 检索 | 更新日期: 2023-09-27 18:16:25
我正在用c#开发一个客户端应用程序,并在本地创建了一个证书。现在我需要在streamsocketcontrol对象中传递证书。例如:
socket = new StreamSocket();
Windows.Security.Cryptography.Certificates.Certificate certificate = await GetClientCert();
StreamSocketControl scontrol = socket.Control;
scontrol.ClientCertificate = certificate;
然后我打电话:
ConnectAsync(hostname, port, tls1.2);
我需要了解GetClientCert()在c#中的实现?
如果您需要从计算机上的证书存储库之一获取证书,您可以执行以下操作:
var clientCertificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
clientCertificateStore.Open(OpenFlags.ReadOnly);
var clientCert = clientCertificateStore.Certificates.Cast<X509Certificate2>().FirstOrDefault(c => c.Issuer.Contains("MyIssuerName"));
试试这个。此选项与UWP
兼容public async Task<Certificate> GetClientCert()
{
try {
Windows.Storage.StorageFile sampleFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Certificate/clients.pfx"));
IBuffer certBuffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);
String encodedCertificate = CryptographicBuffer.EncodeToBase64String(certBuffer);
Certificate crt = new Certificate(certBuffer);
return crt;
}catch(Exception e)
{
Debug.WriteLine(e.ToString());
}
return null;
}