2022-05-24

Why doesn't my sslstream get the certificate from a mail server?

From my code below, I should be getting the certificate of the mail server "mailgw.th-nuernberg.de".

That didn't work and I get the error "the handshake failed due to an unexpected packet format" by calling the method "AuthenticateAsClient".

I tried the same code with the mail server "smtp.gmail.com" on port 993. That works and I get the full certificate. The mail server "mailgw.th-nuernberg.de" exists but I don't know why Google's mail server is working and it isn't.

Here is my Code:

X509Certificate2 cert = null;
var client = new TcpClient("mailgw.th-nuernberg.de", 25);
var certValidation = new RemoteCertificateValidationCallback(delegate (object snd, X509Certificate certificate,
            X509Chain chainLocal, SslPolicyErrors sslPolicyErrors)
{
    return true; //Accept every certificate, even if it's invalid
});

// Create an SSL stream and takeover client's stream
using (var sslStream = new SslStream(client.GetStream(), true, certValidation))
{
    sslStream.AuthenticateAsClient("mailgw.th-nuernberg.de", null, System.Security.Authentication.SslProtocols.Tls13 | System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11, true);
    var serverCertificate = sslStream.RemoteCertificate;
    cert = new X509Certificate2(serverCertificate);
    //System.Diagnostics.Debug.WriteLine("Heruntergeladenes Zertifikat: " + cert);
}
}
catch (Exception e)
{
    System.Diagnostics.Debug.WriteLine(e.Message);
    //throw some fancy exception ;-)
}

Does anyone know what the problem is? What's the difference using the Google mail server instead of using the mail server from my University?



No comments:

Post a Comment