如何在Powershell中使用客户端证书创建TCP客户端连接

时间:2012-01-26 12:50:56

标签: ssl powershell sslstream system.net.sockets

使用以下代码,我可以建立SSL连接:

   $cert = dir cert:\CurrentUser\My | where {$_.Subject -like "*Alice*"}

   $computerName = "google.com"
   $port = "443"

   $socket = New-Object Net.Sockets.TcpClient($computerName, $port)
   $stream = $socket.GetStream()

   $sslStream = New-Object System.Net.Security.SslStream $stream,$false
   $sslStream.AuthenticateAsClient($computerName)


    $sslStream

这个工作正常。但现在我不想添加身份验证的客户端证书。 我想我只需要替换

$sslStream.AuthenticateAsClient($computerName)

$sslStream.BeginAuthenticateAsClient($computerName,$cert,"SslProtocols",$false,"Foo" ,"Bar")

但我没有幸运得到正确的论据。可以Sombody解决Assync Calls ;-) 也许我需要一些C#代码?!?

参数是:

System.IAsyncResult BeginAuthenticateAsClient(

string targetHost, 
System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, 
System.Security.Authentication.SslProtocols enabledSslProtocols,
bool checkCertificateRevocation, 
System.AsyncCallback asyncCallback, 
System.Object asyncState)

我最终想要实现的是列出并稍后指定客户端连接到的CipherSuite。 (我可以使用Wireshark,我知道;-))

2 个答案:

答案 0 :(得分:3)

最后得到它的工作,不是参数4,但是没有收集的$ Cert。

   $cert = dir cert:\CurrentUser\My | where {$_.Subject -like "*alice*"}

   $computerName = "google.com"
   $port = "443"

    [System.Security.Authentication.SslProtocols]$protocol = "ssl3"

   $certcol = New-object System.Security.Cryptography.X509Certificates.X509CertificateCollection
   $certcol.Add($cert)




   $socket = New-Object Net.Sockets.TcpClient($computerName, $port)
   $stream = $socket.GetStream()

   $sslStream = New-Object System.Net.Security.SslStream $stream,$false
   #$sslStream.AuthenticateAsClient($computerName)
   $sslStream.AuthenticateAsClient($computerName,$certcol,$protocol,$false) 


    $sslStream

答案 1 :(得分:0)

根据文档,AuthenticateAsClientBeginAuthenticateAsClient之间的区别在于后者是异步使用。

您应该尝试AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean),其中第二个参数是可以使用的客户端证书的集合(最好是X509Certificate2,因为您需要与证书关联的私钥才能使用它可用于身份验证)。