|
| 1 | +Imports System.IO |
| 2 | +Imports System.Security.Cryptography.X509Certificates |
| 3 | +Imports System.Text |
| 4 | +Imports System.Security.Authentication |
| 5 | +Imports System.Net.Sockets |
| 6 | +Imports System.Net.Security |
| 7 | +Imports System.Net |
| 8 | +Imports System.Collections |
| 9 | +Imports System.Threading |
| 10 | + |
| 11 | +' NclSslClientAsync |
| 12 | +'<snippet0> |
| 13 | +Namespace Examples.Ssl |
| 14 | + |
| 15 | + ' The following example demonstrates the client side of a |
| 16 | + ' client-server application that communicates using the |
| 17 | + ' SslStream and TcpClient classes. |
| 18 | + ' After connecting to the server and authenticating, |
| 19 | + ' the client sends the server a message, recieves a message from the server, |
| 20 | + ' and then terminates. Messages sent to and from the server are terminated |
| 21 | + ' with '<EOF>'. |
| 22 | + Public Class SslTcpClient |
| 23 | + ' complete is used to terminate the application when all |
| 24 | + ' asynchronous calls have completed or any call has thrown an exception. |
| 25 | + ' complete might be used by any of the callback methods. |
| 26 | + Shared complete As Boolean = False |
| 27 | + ' e stores any exception thrown by an asynchronous method so that |
| 28 | + ' the mail application thread can display the exception and terminate gracefully. |
| 29 | + ' e might be used by any of the callback methods. |
| 30 | + Shared e As Exception = Nothing |
| 31 | + ' <snippet8> |
| 32 | + ' readData and buffer holds the data read from the server. |
| 33 | + ' They is used by the ReadCallback method. |
| 34 | + Shared readData As New StringBuilder() |
| 35 | + Shared buffer As Byte() = New Byte(2048) {} |
| 36 | + ' </snippet8> |
| 37 | + '<snippet1> |
| 38 | + |
| 39 | + ' The following method is invoked by the CertificateValidationDelegate. |
| 40 | + Public Shared Function ValidateServerCertificate( |
| 41 | + sender As Object, |
| 42 | + certificate As X509Certificate, |
| 43 | + chain As X509Chain, |
| 44 | + sslPolicyErrors As SslPolicyErrors) As Boolean |
| 45 | + |
| 46 | + Console.WriteLine("Validating the server certificate.") |
| 47 | + |
| 48 | + If sslPolicyErrors = SslPolicyErrors.None Then Return True |
| 49 | + |
| 50 | + |
| 51 | + Console.WriteLine("Certificate error: {0}", sslPolicyErrors) |
| 52 | + |
| 53 | + ' Do not allow this client to communicate with unauthenticated servers. |
| 54 | + Return False |
| 55 | + End Function |
| 56 | + '</snippet1> |
| 57 | + '<snippet2> |
| 58 | + Public Shared Function SelectLocalCertificate( |
| 59 | + sender As Object, |
| 60 | + targetHost As String, |
| 61 | + localCertificates As X509CertificateCollection, |
| 62 | + remoteCertificate As X509Certificate, |
| 63 | + acceptableIssuers As String()) As X509Certificate |
| 64 | + |
| 65 | + Console.WriteLine("Client is selecting a local certificate.") |
| 66 | + |
| 67 | + If acceptableIssuers IsNot Nothing AndAlso acceptableIssuers.Length > 0 AndAlso |
| 68 | + localCertificates IsNot Nothing AndAlso localCertificates.Count > 0 Then |
| 69 | + ' Use the first certificate that is from an acceptable issuer. |
| 70 | + For Each certificate As X509Certificate In localCertificates |
| 71 | + Dim issuer As String = certificate.Issuer |
| 72 | + If Array.IndexOf(acceptableIssuers, issuer) <> -1 Then |
| 73 | + Return certificate |
| 74 | + End If |
| 75 | + Next |
| 76 | + End If |
| 77 | + |
| 78 | + If localCertificates IsNot Nothing AndAlso localCertificates.Count > 0 Then |
| 79 | + Return localCertificates(0) |
| 80 | + End If |
| 81 | + |
| 82 | + Return Nothing |
| 83 | + End Function |
| 84 | + '</snippet2> |
| 85 | + '<snippet3> |
| 86 | + Shared Sub AuthenticateCallback(ar As IAsyncResult) |
| 87 | + |
| 88 | + Dim stream = CType(ar.AsyncState, SslStream) |
| 89 | + |
| 90 | + Try |
| 91 | + stream.EndAuthenticateAsClient(ar) |
| 92 | + Console.WriteLine("Authentication succeeded.") |
| 93 | + Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength) |
| 94 | + Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength) |
| 95 | + Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength) |
| 96 | + Console.WriteLine("Protocol: {0}", stream.SslProtocol) |
| 97 | + ' Encode a test message into a byte array. |
| 98 | + ' Signal the end of the message using the "<EOF>". |
| 99 | + Dim message As Byte() = Encoding.UTF8.GetBytes("Hello from the client.<EOF>") |
| 100 | + ' Asynchronously send a message to the server. |
| 101 | + stream.BeginWrite(message, 0, message.Length, New AsyncCallback(AddressOf WriteCallback), stream) |
| 102 | + Catch authenticationException As Exception |
| 103 | + e = authenticationException |
| 104 | + complete = True |
| 105 | + Return |
| 106 | + End Try |
| 107 | + |
| 108 | + End Sub |
| 109 | + '</snippet3> |
| 110 | + '<snippet4> |
| 111 | + Shared Sub WriteCallback(ar As IAsyncResult) |
| 112 | + Dim stream = CType(ar.AsyncState, SslStream) |
| 113 | + Try |
| 114 | + Console.WriteLine("Writing data to the server.") |
| 115 | + stream.EndWrite(ar) |
| 116 | + ' Asynchronously read a message from the server. |
| 117 | + stream.BeginRead(buffer, 0, buffer.Length, New AsyncCallback(AddressOf ReadCallback), stream) |
| 118 | + Catch writeException As Exception |
| 119 | + e = writeException |
| 120 | + complete = True |
| 121 | + Return |
| 122 | + End Try |
| 123 | + End Sub |
| 124 | + '</snippet4> |
| 125 | + '<snippet5> |
| 126 | + |
| 127 | + Shared Sub ReadCallback(ar As IAsyncResult) |
| 128 | + ' Read the message sent by the server. |
| 129 | + ' The end of the message is signaled using the |
| 130 | + ' "<EOF>" marker. |
| 131 | + Dim stream = CType(ar.AsyncState, SslStream) |
| 132 | + Dim byteCount As Integer |
| 133 | + Try |
| 134 | + Console.WriteLine("Reading data from the server.") |
| 135 | + byteCount = stream.EndRead(ar) |
| 136 | + ' Use Decoder class to convert from bytes to UTF8 |
| 137 | + ' in case a character spans two buffers. |
| 138 | + Dim decoder As Decoder = Encoding.UTF8.GetDecoder() |
| 139 | + Dim chars = New Char(decoder.GetCharCount(buffer, 0, byteCount)) {} |
| 140 | + decoder.GetChars(buffer, 0, byteCount, chars, 0) |
| 141 | + readData.Append(chars) |
| 142 | + ' Check for EOF or an empty message. |
| 143 | + If readData.ToString().IndexOf("<EOF>") = -1 AndAlso byteCount <> 0 Then |
| 144 | + ' We are not finished reading. |
| 145 | + ' Asynchronously read more message data from the server. |
| 146 | + stream.BeginRead(buffer, 0, buffer.Length, New AsyncCallback(AddressOf ReadCallback), stream) |
| 147 | + Else |
| 148 | + Console.WriteLine("Message from the server: {0}", readData.ToString()) |
| 149 | + End If |
| 150 | + Catch readException As Exception |
| 151 | + e = readException |
| 152 | + complete = True |
| 153 | + Return |
| 154 | + End Try |
| 155 | + complete = True |
| 156 | + End Sub |
| 157 | + '</snippet5> |
| 158 | + '<snippet7> |
| 159 | + Public Shared Function Main(args As String()) As Integer |
| 160 | + |
| 161 | + Dim serverName As String |
| 162 | + If args Is Nothing OrElse args.Length < 2 Then |
| 163 | + Console.WriteLine("To start the client specify the host name and" + |
| 164 | + " one or more client certificate file names.") |
| 165 | + Return 1 |
| 166 | + End If |
| 167 | + '<snippet6> |
| 168 | + ' Server name must match the host name and the name on the host's certificate. |
| 169 | + serverName = args(0) |
| 170 | + ' Create a TCP/IP client socket. |
| 171 | + Dim client As New TcpClient(serverName, 80) |
| 172 | + Console.WriteLine("Client connected.") |
| 173 | + ' Create an SSL stream that will close the client's stream. |
| 174 | + Dim sslStream As New SslStream( |
| 175 | + client.GetStream(), False, |
| 176 | + New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), |
| 177 | + New LocalCertificateSelectionCallback(AddressOf SelectLocalCertificate)) |
| 178 | + '</snippet6> |
| 179 | + ' Create the certificate collection to hold the client's certificate. |
| 180 | + Dim clientCertificates As New X509CertificateCollection() |
| 181 | + Dim i = 1 |
| 182 | + While i < args.Length |
| 183 | + Dim certificate As X509Certificate = X509Certificate.CreateFromCertFile(args(i)) |
| 184 | + clientCertificates.Add(certificate) |
| 185 | + i += 1 |
| 186 | + End While |
| 187 | + |
| 188 | + ' Begin authentication. |
| 189 | + ' The server name must match the name on the server certificate. |
| 190 | + sslStream.BeginAuthenticateAsClient( |
| 191 | + serverName, clientCertificates, |
| 192 | + SslProtocols.Ssl3, True, |
| 193 | + New AsyncCallback(AddressOf AuthenticateCallback), sslStream) |
| 194 | + |
| 195 | + ' User can press a key to exit application, or let the |
| 196 | + ' asynchronous calls continue until they complete. |
| 197 | + Console.WriteLine("To quit, press the enter key.") |
| 198 | + |
| 199 | + Do |
| 200 | + ' Real world applications would do work here |
| 201 | + ' while waiting for the asynchronous calls to complete. |
| 202 | + Thread.Sleep(100) |
| 203 | + Loop While complete <> True AndAlso Console.KeyAvailable = False |
| 204 | + |
| 205 | + If Console.KeyAvailable Then |
| 206 | + Console.ReadLine() |
| 207 | + Console.WriteLine("Quitting.") |
| 208 | + client.Close() |
| 209 | + sslStream.Close() |
| 210 | + Return 1 |
| 211 | + End If |
| 212 | + |
| 213 | + If e IsNot Nothing Then |
| 214 | + Console.WriteLine("An exception was thrown: {0}", e.ToString()) |
| 215 | + End If |
| 216 | + |
| 217 | + sslStream.Close() |
| 218 | + client.Close() |
| 219 | + Console.WriteLine("Good bye.") |
| 220 | + Return 0 |
| 221 | + |
| 222 | + End Function |
| 223 | + '</snippet7> |
| 224 | + |
| 225 | + End Class |
| 226 | + |
| 227 | +End Namespace |
0 commit comments