TCP / TLS issue

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of casparoff casparoff 1 year ago.

  • Author
  • #31022
    Profile photo of casparoff

    Hi All.

    I'm trying to make TCP / TLS connection and I keep getting:

    Exception calling "AuthenticateAsClient" with "1" argument(s): "The handshake failed due to an unexpected packet format.

    My code is below:

    $tcpClient = New-Object System.Net.Sockets.TcpClient($ipAddress, $port)
    $stream = $tcpClient.GetStream()
    $sslStream = New-Object System.Net.Security.SslStream $stream,$false

    I'm thinking that using this constructor for TcpClient could help

    But I don't know how to create validation delegate in powershell.

    Could someone please point me to some direction?

  • #31029
    Profile photo of Dave Wyatt
    Dave Wyatt

    PowerShell will allow you to pass any ScriptBlock object to a .NET method which expects a delegate or Func/Action object. In this case, RemoteCertificateValidationCallback is passed 4 arguments, and expected to return a bool, so you could do this:

    $delegate = {
        param (
            [object] $Sender,
            [System.Security.Cryptography.X509Certificates.X509Certificate] $Certificate,
            [System.Security.Cryptography.X509Certificates.X509Chain] $Chain,
            [System.Net.Security.SslPolicyErrors] $SslPolicyErrors
        # some logic here
        return $true
    $sslStream = New-Object System.Net.Security.SslStream($stream, $false, $delegate)

    You don't have to use a param block if you don't want to (in which case you would refer to $args[0] through $args[3]), and you don't have to assign the delegate to another variable before calling your constructor, but those things can often make the code easier to read.

  • #31043
    Profile photo of casparoff

    Thank you Dave 🙂 I will try this

You must be logged in to reply to this topic.