本文整理匯總了VB.NET中System.Net.Security.SslStream類的典型用法代碼示例。如果您正苦於以下問題:VB.NET SslStream類的具體用法?VB.NET SslStream怎麽用?VB.NET SslStream使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了SslStream類的2個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的VB.NET代碼示例。
示例1: RunServer
' 導入命名空間
Imports System.Collections
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.Security
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Namespace Examples.System.Net
Public NotInheritable Class SslTcpServer
Shared serverCertificate As X509Certificate = Nothing
' The certificate parameter specifies the name of the file
' containing the machine certificate.
Public Shared Sub RunServer(certificate As String)
serverCertificate = X509Certificate.CreateFromCertFile(certificate)
' Create a TCP/IP (IPv4) socket And listen for incoming connections.
Dim listener = New TcpListener(IPAddress.Any, 8080)
listener.Start()
While True
Console.WriteLine("Waiting for a client to connect...")
' Application blocks while waiting for an incoming connection.
' Type CNTL-C to terminate the server.
Dim client As TcpClient = listener.AcceptTcpClient()
ProcessClient(client)
End While
End Sub
Private Shared Sub ProcessClient(client As TcpClient)
' A client has connected. Create the
' SslStream using the client's network stream.
Dim sslStream = New SslStream(client.GetStream(), False)
Try
sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired:=False, checkCertificateRevocation:=True)
' Display the properties And settings for the authenticated stream.
DisplaySecurityLevel(sslStream)
DisplaySecurityServices(sslStream)
DisplayCertificateInformation(sslStream)
DisplayStreamProperties(sslStream)
' Set timeouts for the read and write to 5 seconds.
sslStream.ReadTimeout = 5000
sslStream.WriteTimeout = 5000
' Read a message from the client.
Console.WriteLine("Waiting for client message...")
Dim messageData As String = ReadMessage(sslStream)
Console.WriteLine("Received: {0}", messageData)
' Write a message to the client.
Dim message As Byte() = Encoding.UTF8.GetBytes("Hello from the server.<EOF>")
Console.WriteLine("Sending hello message.")
sslStream.Write(message)
Catch e As AuthenticationException
Console.WriteLine("Exception: {0}", e.Message)
If e.InnerException IsNot Nothing Then
Console.WriteLine("Inner exception: {0}", e.InnerException.Message)
End If
Console.WriteLine("Authentication failed - closing the connection.")
sslStream.Close()
client.Close()
Return
Finally
' The client stream will be closed with the sslStream
' because we specified this behavior when creating
' the sslStream.
sslStream.Close()
client.Close()
End Try
End Sub
Private Shared Function ReadMessage(sslStream As SslStream) As String
' Read the message sent by the client.
' The client signals the end of the message using the
' "<EOF>" marker.
Dim buffer As Byte() = New Byte(2048) {}
Dim messageData As StringBuilder = New StringBuilder()
Dim bytes As Integer = -1
Do
' Read the client's test message.
bytes = sslStream.Read(buffer, 0, buffer.Length)
' Use decoder class to convert from bytes to UTF8
' in case a character spans two buffers.
Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
Dim chars As Char() = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
decoder.GetChars(buffer, 0, bytes, chars, 0)
messageData.Append(chars)
' Check for EOF or an empty message.
If messageData.ToString().IndexOf("<EOF>") <> -1 Then
Exit Do
End If
Loop While bytes <> 0
Return messageData.ToString()
End Function
Private Shared Sub DisplaySecurityLevel(stream As SslStream)
Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength)
Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength)
Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength)
Console.WriteLine("Protocol: {0}", stream.SslProtocol)
End Sub
Private Shared Sub DisplaySecurityServices(stream As SslStream)
Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer)
Console.WriteLine("IsSigned: {0}", stream.IsSigned)
Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted)
End Sub
Private Shared Sub DisplayStreamProperties(stream As SslStream)
Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite)
Console.WriteLine("Can timeout: {0}", stream.CanTimeout)
End Sub
Private Shared Sub DisplayCertificateInformation(stream As SslStream)
Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus)
Dim localCertificate As X509Certificate = stream.LocalCertificate
If stream.LocalCertificate IsNot Nothing Then
Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.", localCertificate.Subject, localCertificate.GetEffectiveDateString(), localCertificate.GetExpirationDateString())
Else
Console.WriteLine("Local certificate is null.")
End If
' Display the properties of the client's certificate.
Dim remoteCertificate As X509Certificate = stream.RemoteCertificate
If stream.RemoteCertificate IsNot Nothing Then
Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.", remoteCertificate.Subject, remoteCertificate.GetEffectiveDateString(), remoteCertificate.GetExpirationDateString())
Else
Console.WriteLine("Remote certificate is null.")
End If
End Sub
Private Shared Sub DisplayUsage()
Console.WriteLine("To start the server specify:")
Console.WriteLine("serverSync certificateFile.cer")
Environment.[Exit](1)
End Sub
Public Shared Function Main(ByVal args As String()) As Integer
Dim certificate As String
If args Is Nothing OrElse args.Length < 1 Then
DisplayUsage()
End If
certificate = args(0)
RunServer(certificate)
Return 0
End Function
End Class
End Namespace
示例2: RunClient
' 導入命名空間
Imports System.Collections
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Namespace Examples.System.Net
Public Class SslTcpClient
' The following method is invoked by the RemoteCertificateValidationDelegate.
Public Shared Function ValidateServerCertificate(
sender As Object,
certificate As X509Certificate,
chain As X509Chain,
sslPolicyErrors As SslPolicyErrors) As Boolean
If sslPolicyErrors = SslPolicyErrors.None Then Return True
Console.WriteLine("Certificate error: {0}", sslPolicyErrors)
' Do not allow this client to communicate with unauthenticated servers.
Return False
End Function
Public Shared Sub RunClient(machineName As String, serverName As String)
' Create a TCP/IP client socket.
' machineName is the host running the server application.
Dim client = New TcpClient(machineName, 443)
Console.WriteLine("Client connected.")
' Create an SSL stream that will close the client's stream.
Dim sslStream = New SslStream(
client.GetStream(), False,
New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), Nothing)
' The server name must match the name on the server certificate.
Try
sslStream.AuthenticateAsClient(serverName)
Catch e As AuthenticationException
Console.WriteLine("Exception: {0}", e.Message)
If e.InnerException IsNot Nothing Then
Console.WriteLine("Inner exception: {0}", e.InnerException.Message)
End If
Console.WriteLine("Authentication failed - closing the connection.")
client.Close()
Return
End Try
' Encode a test message into a byte array.
' Signal the end of the message using the "<EOF>".
Dim messsage As Byte() = Encoding.UTF8.GetBytes("Hello from the client.<EOF>")
' Send hello message to the server.
sslStream.Write(messsage)
sslStream.Flush()
' Read message from the server.
Dim serverMessage = ReadMessage(sslStream)
Console.WriteLine("Server says: {0}", serverMessage)
' Close the client connection
client.Close()
Console.WriteLine("Client closed.")
End Sub
Private Shared Function ReadMessage(sslStream As SslStream) As String
' Read the message sent by the server.
' The end of the message is signaled using the "<EOF>" marker.
Dim buffer = New Byte(2048) {}
Dim messageData = New StringBuilder()
Dim bytes As Integer
Do
bytes = sslStream.Read(buffer, 0, buffer.Length)
' Use Decoder class to convert from bytes to UTF8
' in case a character spans two buffers.
Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
Dim chars = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
decoder.GetChars(buffer, 0, bytes, chars, 0)
messageData.Append(chars)
' Check for EOF.
If messageData.ToString().IndexOf("<EOF>") <> -1 Then Exit Do
Loop While bytes <> 0
Return messageData.ToString()
End Function
Private Shared Sub DisplayUsage()
Console.WriteLine("To start the client specify:")
Console.WriteLine("clientSync machineName [serverName]")
Environment.[Exit](1)
End Sub
Public Shared Function Main(args As String()) As Integer
Dim serverCertificateName As String
Dim machineName As String
If args Is Nothing OrElse args.Length < 1 Then
DisplayUsage()
End If
' User can specify the machine name and server name.
' Server name must match the name on the server's certificate.
machineName = args(0)
If args.Length < 2 Then
serverCertificateName = machineName
Else
serverCertificateName = args(1)
End If
SslTcpClient.RunClient(machineName, serverCertificateName)
Return 0
End Function
End Class
End Namespace