i wanna setup a SSL connection, but really don't know everything about SSL handshake rules and life cycle. i wrote a code
void main()
{
TcpClient client = new TcpClient("192.168.1.160", 4113);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
new LocalCertificateSelectionCallback(localCertSelection)
);
sslStream.AuthenticateAsClient(serverName);
}
public X509Certificate localCertSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate 开发者_StackOverflow社区remoteCertificate, string[] acceptableIssuers)
{// why here 'remoteCertificate' parameter is empty? 'acceptableIssuers' and 'localCertificates' too
string cert = "MIIEwjCCA6qgAwIBAgIBADANBgkqhkiG9w...";
X509Certificate clientCert = new X509Certificate(System.Text.Encoding.ASCII.GetBytes(cert));
return clientCert;
}
public bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// 'certificate' has data now. it has come from server
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
when i run the code, program flow first goes to 'localCertSelection' method and then goes to 'ValidateServerCertificate' method.
in 'localCertSelection' method 'remoteCertificate' is empty , but in 'ValidateServerCertificate' method 'certificate' has data. it has come from server, but why 'sslPolicyErrors' is 'RemoteCertificateNameMismatch | RemoteCertificateChainErrors' ? what's wrong? what i have to do?The RemoteCertificateNameMismatch
error may occur if your "servername" are wrong. I mean that servername in
sslStream.AuthenticateAsClient(serverName);
must be "192.168.1.160", the same as in
TcpClient client = new TcpClient("192.168.1.160", 4113);
The RemoteCertificateChainErrors
happen if something wrong with your root certificate. When you create certificate you have to put appropriate host in CN,
CN=192.168.1.160. And don't forget import your root certificate to "Trusted Root Certification Authorities".
精彩评论