我有这个代码:
string certificateFilePath = @"C:\Users\Administrator\Documents\Certificate.pfx";
string certificateFilePassword = "Some Password Here";
X509Certificate clientCertificate = new X509Certificate(certificateFilePath, certificateFilePassword);
TcpClient client = new TcpClient(host, port);
SslStream stream = new SslStream(client.GetStream(), false, (sender, certificate, chain, errors) => true);
X509CertificateCollection clientCertificates = new X509CertificateCollection {clientCertificate};
stream.AuthenticateAsClient(host, clientCertificates, SslProtocols.Tls, false);
当我在控制台应用程序中运行代码时,一切正常,stream.IsAuthenticated
并stream.IsMutuallyAuthenticated
返回true
并stream.LocalCertificate
包含正确的证书对象。
但是,当在 a 中运行完全相同的代码时Windows Service (as LOCAL SYSTEM user)
,虽然stream.IsAuthenticated
返回true
、stream.IsMutuallyAuthenticated
返回false
和stream.LocalCertificate
返回null
。
在这两种情况下都会发生这种情况,在第一行运行后clientCertificate
加载正确的证书数据并包含证书的正确信息Subject
和Issuer
.
我还尝试使用以下代码强制 SslStream 选择证书:
string certificateFilePath = @"C:\Users\Administrator\Documents\Certificate.pfx";
string certificateFilePassword = "Some Password Here";
X509Certificate clientCertificate = new X509Certificate(certificateFilePath, certificateFilePassword);
TcpClient client = new TcpClient(host, port);
SslStream stream = new SslStream(client.GetStream(), false, (sender, certificate, chain, errors) => true, (sender, host, certificates, certificate, issuers) => clientCertificate);
X509CertificateCollection clientCertificates = new X509CertificateCollection {clientCertificate};
stream.AuthenticateAsClient(host, clientCertificates, SslProtocols.Tls, false);
但是代码仍然不起作用并stream.IsMutuallyAuthenticated
返回false
和stream.LocalCertificate
返回null
。
我已经探索了几天了,但我无法弄清楚。非常感谢任何帮助。
编辑:使用WinHttpCertCfg工具 尝试证书后,结果发现与类似问题不同,LOCAL SYSTEM 帐户已经可以访问目标证书的私钥,如下图所示: 因此问题仍未解决。