M
M
mastersoftna2011-09-27 14:10:12
C++ / C#
mastersoftna, 2011-09-27 14:10:12

OpenSSL and C#

Hi all!

Explain to me please. how to determine in what format this or that smtp server works: ssl or tls. Wrote a client in c#. I connect. I read server commands. I see the STARTTLS command. Responding to the STARTTLS server. What to do next? How can openssl be used here? Otherwise, I can't parse the commands. means ssl. I am using openssl functions. I send ehlo and get a response. but the second command does not work. You can give an example code for working with ssl and tls. Problems with gmail. The standard framework sslstream is not suitable because I am writing for the compact framework.

Example of my code:

private string Response()
{
string sResponse = "";
byte[] bytes = new byte[1024];

System.Text.ASCIIEncoding oEncodedData = new System.Text.ASCIIEncoding();
NetworkStream NetStream = tcpClient.GetStream();
if (tls)
{
SslStream ss = new SslStream(NetStream, false, new RemoteCertificateValidationHandler(CertificateValidationCallback), null);

ss.AuthenticateAsClient("smtp.gmail.com");
while (tcpClient.Available == 0)
{
System.Threading.Thread.Sleep(100);
}
ss.Read(bytes, 0, tcpClient.Available);
sResponse = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
else
{
while (tcpClient.Available == 0)
{
System.Threading.Thread.Sleep(100);
}
NetStream.Read(bytes, 0, tcpClient.Available);
sResponse = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
return sResponse;
}

static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, int tmp, VerifyResult vr)
{
/*if (sslPolicyErrors != SslPolicyErrors.None)
{
Console.WriteLine("SSL Certificate Validation Error!");
Console.WriteLine(sslPolicyErrors.ToString());
return false;
}
else*/
return true;
}

private void Write(string sMessage)
{
System.Text.ASCIIEncoding oEncodedData = new System.Text.ASCIIEncoding();
byte[] WrriteBuffer = new byte[1024];
WrriteBuffer = oEncodedData.GetBytes(sMessage);
NetworkStream NetStream = tcpClient.GetStream();
if (tls)
{

SslStream ss = new SslStream(NetStream, false, new RemoteCertificateValidationHandler(CertificateValidationCallback), null);
ss.AuthenticateAsClient("smtp.gmail.com");
ss.Write(WrriteBuffer, 0, WrriteBuffer.Length);

}
else
{
NetStream.Write(WrriteBuffer, 0, WrriteBuffer.Length);
}
}

/// /// Отпрвляем письмо
///
/// само письмо
///
public bool Send(NANMessage msg)
{
string result = "";
int tmp = msg.From.IndexOf("@", 0, msg.From.Length);
string domain = msg.From.Substring(tmp + 1, msg.From.Length - tmp - 1);

result = Response();
if (result.Substring(0, 3) != "220")
{
throw new SMTPException(result);
}
Write("EHLO "+ domain + "\r\n");
result = Response();
if (result.Substring(0, 3) != "250")
{
throw new SMTPException(result);
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question