Hallo,
Ich bin mittlerweile am verzweifeln. Ich versuche einen SSL Socket Server zum laufen zu bringen, scheitere aber am Zertifikat. Fehlermeldung: "Servermodus-SSL muss ein Zertifikat mit dem verknüpften privaten Schlüssel verwenden.".
Mein Zertifikatsfile enthält aber zu 100% einen Privten schlüssel.
Habt ihr einen Tipp für mich was das sein könnte?
Server:
Aufruf im Windows Form zum testen:
Client:
Ich bin euch dankbar für jede Hilfe!
lg
Ich bin mittlerweile am verzweifeln. Ich versuche einen SSL Socket Server zum laufen zu bringen, scheitere aber am Zertifikat. Fehlermeldung: "Servermodus-SSL muss ein Zertifikat mit dem verknüpften privaten Schlüssel verwenden.".
Mein Zertifikatsfile enthält aber zu 100% einen Privten schlüssel.
Habt ihr einen Tipp für mich was das sein könnte?
Server:
VB.NET-Quellcode
- 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
- Imports System.Threading
- Public NotInheritable Class SignServerSSL
- Private Shared serverCertificate As New X509Certificate
- ' The certificate parameter specifies the name of the file
- ' containing the machine certificate.
- Private Shared Sub initCertificate()
- ' serverCertificate = New X509Certificate(GlobalSettings.CertFile, "fidus")
- serverCertificate.Import(GlobalSettings.CertFile, "geheim", X509KeyStorageFlags.MachineKeySet)
- End Sub
- Public Shared Sub ListenForClients()
- initCertificate()
- ' Create a TCP/IP (IPv4) socket and listen for incoming connections.
- 'Dim ip As System.Net.IPAddress = New IPAddress("192.168.1.1")
- Dim ipAddress As System.Net.IPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList(0)
- 'Dim ipAddress As System.Net.IPAddress = IPAddress.Any
- Dim Port As Integer = 8080
- Dim listener As New TcpListener(ipAddress, Port)
- log.entry("Starting Server on " & ipAddress.ToString & ":" & Port)
- listener.Start()
- While True
- log.entry("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()
- log.entry("StartListener")
- Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf ProcessClient))
- clientThread.Start(client)
- End While
- End Sub
- Private Shared Sub ProcessClient(client As TcpClient)
- log.entry("Incoming Client ...")
- ' A client has connected. Create the
- ' SslStream using the client's network stream.
- Dim sslStream As New SslStream(client.GetStream(), False)
- ' Authenticate the server but don't require the client to authenticate.
- Try
- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
- 'Hier wird die Exception geworfen: Servermodus-SSL muss ein Zertifikat mit dem verknüpften privaten Schlüssel verwenden."}
- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
- sslStream.AuthenticateAsServer(serverCertificate, False, SslProtocols.Tls, 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.
- log.entry("Waiting for client message...")
- Dim messageData As String = ReadMessage(sslStream)
- log.entry("Received: " & messageData & "")
- ' Write a message to the client.
- Dim message As Byte() = Encoding.UTF8.GetBytes("Hello from the server.<EOF>")
- log.entry("Sending hello message.")
- sslStream.Write(message)
- Catch e As AuthenticationException
- log.entry("Exception: " & e.Message & "")
- If e.InnerException IsNot Nothing Then
- log.entry("Inner exception: " & e.InnerException.Message & "")
- End If
- log.entry("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
- Try
- log.entry("Start reading Message")
- ' 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(2047) {}
- Dim messageData As 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()
- Catch ex As Exception
- log.entry(ex)
- Return "<KEINE DATEN EMPFANGEN>"
- End Try
- End Function
- Private Shared Sub DisplaySecurityLevel(stream As SslStream)
- log.entry("Cipher: " & stream.CipherAlgorithm & " strength " & stream.CipherStrength)
- log.entry("Hash: " & stream.HashAlgorithm & " strength " & stream.HashStrength & "")
- log.entry("Key exchange: " & stream.KeyExchangeAlgorithm & " strength " & stream.KeyExchangeStrength & "")
- log.entry("Protocol: " & stream.SslProtocol & "")
- End Sub
- Private Shared Sub DisplaySecurityServices(stream As SslStream)
- log.entry("Is authenticated: " & stream.IsAuthenticated & " as server? " & stream.IsServer & "")
- log.entry("IsSigned: " & stream.IsSigned & "")
- log.entry("Is Encrypted: " & stream.IsEncrypted & "")
- End Sub
- Private Shared Sub DisplayStreamProperties(stream As SslStream)
- log.entry("Can read: " & stream.CanRead & ", write " & stream.CanWrite & "")
- log.entry("Can timeout: " & stream.CanTimeout & "")
- End Sub
- Private Shared Sub DisplayCertificateInformation(stream As SslStream)
- log.entry("Certificate revocation list checked: " & stream.CheckCertRevocationStatus & "")
- Dim localCertificate As X509Certificate = stream.LocalCertificate
- If stream.LocalCertificate IsNot Nothing Then
- log.entry("Local cert was issued to " & localCertificate.Subject & " and is valid from " & localCertificate.GetEffectiveDateString() & " until " & localCertificate.GetExpirationDateString() & ".")
- Else
- log.entry("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
- log.entry("Remote cert was issued to " & remoteCertificate.Subject & " and is valid from " & remoteCertificate.GetEffectiveDateString() & " until " & remoteCertificate.GetExpirationDateString() & ".")
- Else
- log.entry("Remote certificate is null.")
- End If
- End Sub
- Private Shared Sub DisplayUsage()
- log.entry("To start the server specify:")
- log.entry("serverSync certificateFile.cer")
- Environment.[Exit](1)
- End Sub
- End Class
Aufruf im Windows Form zum testen:
Client:
VB.NET-Quellcode
- 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
- Public Class ATSignClient
- Private client As TcpClient
- Private sslStream As SslStream
- Private certificateErrors As New Hashtable()
- ' The following method is invoked by the RemoteCertificateValidationDelegate.
- Public Function ValidateServerCertificate(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors__1 As SslPolicyErrors) As Boolean
- ' Return True
- If sslPolicyErrors__1 = SslPolicyErrors.None Then
- Return True
- End If
- If sslPolicyErrors__1 = SslPolicyErrors.RemoteCertificateNameMismatch Then
- MsgBox("Der Servername stimmt mit dem angegebenen Zertifikat nicht überein: " & sslPolicyErrors__1)
- Return True
- End If
- MsgBox("Certificate error: " & sslPolicyErrors__1.ToString)
- ' Do not allow this client to communicate with unauthenticated servers.
- Return False
- End Function
- Public Function Connect(machineName As String, serverName As String)
- ' Create a TCP/IP client socket.
- ' machineName is the host running the server application.
- client = New TcpClient(machineName, 8080)
- ' Create an SSL stream that will close the client's stream.
- sslStream = New SslStream(client.GetStream(), False, New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), Nothing)
- ' The server name must match the name on the server certificate.
- ' MsgBox("Stream erstellt")
- Try
- sslStream.AuthenticateAsClient(serverName)
- ' MsgBox("Authentifiziert!")
- Catch e As AuthenticationException
- Dim msg As String = ""
- msg &= "Exception: " & e.Message
- If e.InnerException IsNot Nothing Then
- msg &= "Inner exception: " & e.InnerException.Message
- End If
- msg &= "Authentication failed - closing the connection."
- client.Close()
- Return msg
- End Try
- ' MsgBox("Warten")
- ' Encode a test message into a byte array.
- ' Signal the end of the message using the "<EOF>".
- 'SendMessage("test123")
- Dim messsage As Byte() = Encoding.UTF8.GetBytes("Test123456789123456789123456789getInfo")
- ' Send hello message to the server.
- sslStream.Write(messsage)
- sslStream.Flush()
- ' Read message from the server.
- Dim serverMessage As String = ReadMessage(sslStream)
- ' Send hello message to the server.
- sslStream.Write(Encoding.UTF8.GetBytes("Zweiter versuch etwas zu senden"))
- sslStream.Flush()
- Return serverMessage
- ' Close the client connection.
- '
- End Function
- Public Function isConnected()
- If IsNothing(client) Then Return False
- Return client.Connected
- End Function
- Public Function SendMessage(ByRef p_msg As String)
- If Not client.Connected Then
- Return "not connected"
- End If
- Dim messsage As Byte() = Encoding.UTF8.GetBytes(p_msg)
- ' Send hello message to the server.
- sslStream.Write(messsage)
- sslStream.Flush()
- ' Read message from the server.
- Dim serverMessage As String = ReadMessage(sslStream)
- sslStream.Flush()
- Return serverMessage
- End Function
- Public Sub disconnect()
- client.Close()
- End Sub
- Private 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 As Byte() = New Byte(2047) {}
- Dim messageData As New StringBuilder()
- Dim bytes As Integer = -1
- 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 As Char() = 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
- End If
- Loop While bytes <> 0
- Return messageData.ToString()
- End Function
- End Class
Ich bin euch dankbar für jede Hilfe!
lg