是否有方法从.p12文件中读取证书,并在使用SSLStreams时将它们用于SSL/TLS通信?
sslstream.AuthenticateAsClient(SERVERNAME, ReadCertificates(), sslProtocol, sslCertRevocationCheck);
private X509Certificate2Collection ReadCertificates()
{
X509Certificate2Collection collection = null;
X509Certificate2Collection collection2 = null;
try
{
String certStore1 = "C:\\Temp\\Certs\\Client.p12";
X509Certificate2 certificate1 = new X509Certificate2(certStore1, "*****");
//Create a collection and add two of the certificates.
collection = new X509Certificate2Collection();
collection.Import(certStore1,"*****",X509KeyStorageFlags.PersistKeySet);
collection2 = new X509Certificate2Collection();
foreach(X509Certificate2 cert in collection)
{
if(cert.HasPrivateKey)
collection2.Add(cert);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("Certificate collection:" + collection.Count);
return collection2;
}除以下异常外,上述代码将失败
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.只有当服务器的公钥被放入Windows密钥存储库时,代码才能工作。
Client.p12包含客户端的私钥和服务器的公钥。
发布于 2022-02-16 11:22:26
在.NET6中,可以使用AuthenticateAsClient和SslClientAuthenticationOptions并设置RemoteCertificateValidationCallback来实现上述目标。
https://stackoverflow.com/questions/71125959
复制相似问题