SslStream.AuthenticateAsClient无法正常工作

时间:2018-02-15 16:18:12

标签: c# https x509certificate2 sslstream

我尝试使用SslStream类连接到https服务器(服务器使用受信任的根证书),但是当我使用SslStream.AuthenticateAsClient(String,X509CertificateCollection,SslProtocols,Boolean)时,程序站立无限制地没有任何例外或继续。 这是代码:

String serverName = "https://192.168.32.74/params.cgi";
String pfxName = @"C:\...\server.pfx";

X509Certificate2 certificate = new X509Certificate2(pfxName, "mypassword");
//Create new X509 store called teststore from the local certificate store.
X509Store store = new X509Store("teststore", StoreLocation.CurrentUser);

//Create a collection and add two of the certificates.
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Add(certificate);

store.Open(OpenFlags.ReadWrite);
store.AddRange(collection);
try
{
    TcpClient client = new TcpClient();
        client.Connect(server, port);
        SslStream sslStream = new SslStream(
            client.GetStream(),
            false,
            new RemoteCertificateValidationCallback(ValidateServerCertificate),
            null);

        sslStream.AuthenticateAsClient(
            serverName,
            collection,
            SslProtocols.Default,
            true);
}
catch (Exception ex)
{
    Console.WriteLine("Exception: {0}", ex.ToString());
}
...

有谁知道我为什么遇到这个问题?

更新

我已使用.pfx文件更新代码

1 个答案:

答案 0 :(得分:0)

因为您尝试在没有私钥的情况下执行客户端证书身份验证(在cerName变量中。您应该使用有效的私钥引用X509Certificate2对象。来自PKCS#12 / PFX文件或来自个人存储。

更新

您需要将server.crtserver.key合并到PFX文件中。将两个文件放在同一个文件夹中(并确保两个名称具有相同的名称)并运行certutil命令:

certutil -mergepfx path\server.crt path\server.pfx

其中path\server.crt是.crt文件的实际路径,path\server.pfx是保存生成的PFX的路径。出现提示时,输入PFX的密码。然后使用X509Certificate2 (String, SecureString)构造函数在代码中获取带私钥的证书。