user1654278
user1654278

Reputation: 67

Send data from Tcp.Client.Socket with ssl Stream in .net c#

Im try to read an xml file and send to server with sslStream. Before send to server i must make Login and after succesfull authorization i must send the fileData. To fileSize is about 300kb. I can make sycessfull the login, but the problem is that server seems to not receive the data that i send. here is the code method1: I suceesfull make login(i receive ok but it seems that i can't send the contents of xml file)

TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);

        sendStream.Write(Encoding.UTF8.GetBytes("Login\r\n" + username + "\r\n" + password + "\r\n"));
        sendStream.Flush();
        int bytes = -1;
        byte[] buffer = new byte[2048];

        bytes = sendStream.Read(buffer, 0, buffer.Length);

        string response = Encoding.UTF8.GetString(buffer, 0, bytes);

        if (response.Trim() == "OK")
        {
            MessageBox.Show("Connected");
            byte[] b1 = File.ReadAllBytes(filePath);
            sendStream.Write(Encoding.UTF8.GetBytes("Send\r\n"));
            sendStream.Write(Encoding.UTF8.GetBytes(fileName+"\r\n"));
            sendStream.Write(b1, 0, b1.Length);
            sendStream.Flush();
            sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n"));
            sendStream.Flush();
            sendClient.Close();
        }

and here is a second method with streamWriter

TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);

        StreamWriter writer = new StreamWriter(sendStream);
        writer.WriteLine("Login");
        writer.WriteLine(username);
        writer.WriteLine(password);
        writer.Flush();
        StreamReader reader = new StreamReader(sendStream);
        string response = reader.ReadLine();
        if (response.Trim() == "OK")
        {
            MessageBox.Show("succesfull connect");

            string allText = File.ReadAllText(filePath,Encoding.Default);
            writer.WriteLine("Send");
            writer.WriteLine(fileName);
            writer.WriteLine(allText);
            sendClient.Close();
        }

Upvotes: 0

Views: 3040

Answers (2)

user14103815
user14103815

Reputation:

Do not doubt that the answer to your question is this code

public System.Net.Security.SslStream GetStream(NetworkStream _NetworkStream)
        {
            try
            {
                System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(_NetworkStream, false);
                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: false,
                enabledSslProtocols:
                    System.Security.Authentication.SslProtocols.Default |
                    System.Security.Authentication.SslProtocols.None |
                    System.Security.Authentication.SslProtocols.Tls |
                    System.Security.Authentication.SslProtocols.Tls11 |
                    System.Security.Authentication.SslProtocols.Tls12 |
                    System.Security.Authentication.SslProtocols.Ssl2 |
                    System.Security.Authentication.SslProtocols.Ssl3
                , checkCertificateRevocation: true);
                new SSL().DisplaySecurityLevel(sslStream);
                new SSL().DisplaySecurityServices(sslStream);
                new SSL().DisplayCertificateInformation(sslStream);
                new SSL().DisplayStreamProperties(sslStream);
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                return sslStream;
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
            
        }
public string ReadMessage(System.Net.Security.SslStream sslStream)
        {
            // Read the  message sent by the client.
            // The client signals the end of the message using the
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -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.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);
            // Check for EOF or an empty message.
            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                //break;
            }
            //} while (bytes != 0);

            return messageData.ToString();
        }
        public void DisplaySecurityLevel(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
            Console.WriteLine("Protocol: {0}", stream.SslProtocol);
        }
        public void DisplaySecurityServices(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
            Console.WriteLine("IsSigned: {0}", stream.IsSigned);
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
        }
        public void DisplayStreamProperties(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
        }
        public void DisplayCertificateInformation(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

            System.Security.Cryptography.X509Certificates.X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                    localCertificate.Subject,
                    localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("Local certificate is null.");
            }
            // Display the properties of the client's certificate.
            System.Security.Cryptography.X509Certificates.X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
                Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                    remoteCertificate.Subject,
                    remoteCertificate.GetEffectiveDateString(),
                    remoteCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("Remote certificate is null.");
            }
        }

Upvotes: 0

user1654278
user1654278

Reputation: 67

Ok, one solution is to write all commands as a byte array and copy these to a bigger array. The trick is to add the dataSize as a bigendian number

Upvotes: 0

Related Questions