Hallo Zusammen,
ich habe ein Problem bei der Herstellung einer verschlüsselten Verbindung zu einem Server.
Ich habe mir gedacht, für eine solche Verbindung währe die Klasse
sslStream ganz gut geeignet, aber irgendwas mache ich noch falsch, kann mir jemand sagen was?
Das ist mein Code:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67:
| public static void RunClient(string machineName, string serverName) { TcpClient client = new TcpClient(machineName, 6000); Console.WriteLine("Client connected."); SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), new LocalCertificateSelectionCallback(SelectLocalCertificate)); try { sslStream.AuthenticateAsClient(serverName); } catch (AuthenticationException e) { Console.WriteLine("Exception: {0}", e.Message); if (e.InnerException != null) { Console.WriteLine("Inner exception: {0}", e.InnerException.Message); } Console.WriteLine("Authentication failed - closing the connection."); client.Close(); return; } byte[] messsage = Encoding.UTF8.GetBytes("hallo"); sslStream.Write(messsage); sslStream.Flush(); string serverMessage = ReadMessage(sslStream); Console.WriteLine("Server says: {0}", serverMessage); client.Close(); Console.WriteLine("Client closed."); }
public static X509Certificate SelectLocalCertificate(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { if (acceptableIssuers != null && acceptableIssuers.Length > 0 && localCertificates != null && localCertificates.Count > 0) { foreach (X509Certificate certificate in localCertificates) { string issuer = certificate.Issuer; if (Array.IndexOf(acceptableIssuers, issuer) != -1) return certificate; } } if (localCertificates != null && localCertificates.Count > 0) return localCertificates[0];
return null;
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false; } |
Vielen dank im Voraus.
Grüße Waldemar