473,386 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

I'm having problems with cryptography and sockets, help

Hi.

I'm writing a program, and I need to send confidential data through the
network, so I decided to use encryption, using the
System.Security.Cryptography namespace.

I'm using the sockets for the network communications, and the program first
does a key exchange, with the asymetric cipher classes, to get a new key for
the symmetric cipher. My problem is, that although I have checked that the
two points get to the same key and initialization vector, when the sender
sends the data, its ok, but the receiver gets blocked. I am using blocking
sockets, so I am aware that if the socket does not have received data, it
blocks until it does. But I know that it does receive the data, and still
it blocks, not the NetworkStream, but the CryptoStream used to decrypt the
data. I have been trying many things, using the StreamReader and
StreamWriter like in the documentation examples, but doesn't work.

I need help, please. It's been 2 full days trying, please help.

Alejandro.

Here are some lines of the code:

This is the receiver code (where it blocks, in the Read function):

string mensaje;
NetworkStream stream = clienteTcp.GetStream();
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateDecryptor(tdesClave ,tdesIV),
CryptoStreamMode.Read);
// Búfer de 8Kb
byte[] datos = new byte[8192];
int bytes;
int intentos = 25;
// Detectar si hay datos
while(intentos > 0)
{
if (stream.DataAvailable)
break;
intentos--;
System.Threading.Thread.Sleep(200);
}
// Si no hay datos salir
if (!stream.DataAvailable)
return String.Empty;
// Leer mensaje
bytes = crStream.Read(datos,0,datos.Length);
// Pasar a string
mensaje = System.Text.Encoding.Unicode.GetString(datos,0,byt es);
This is the sender code:

NetworkStream stream = new NetworkStream(clienteTcp);
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateEncryptor(tdesClave ,tdesIV),
CryptoStreamMode.Write);
// Convertir el string a una matriz de bytes
byte[] datos = System.Text.Encoding.Unicode.GetBytes(mensaje);
// Transmitir mensaje
crStream.Write(datos,0,datos.Length);
crStream.Flush();

Nov 16 '05 #1
10 2006
Alejandro,

It looks like you are trying to read too much data. You are issuing a
call to the Read method on the socket class passing in a length of 8192
bytes. If the sender does not send 8192 bytes, the call to Read is going to
block until it gets 8192 bytes.

There are two ways of handling this. The first is to mark your message
with an identifier which indicates that the message has completed
transmission. This would require you to read byte-by-byte, which is not a
good thing.

The second is to actually send the length of the message before you send
the message yourself. This way, you can issue a call to the Read method and
know you are not asking for more data than is on the line.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Alejandro Castañaza" <da*****************@itelgua.com> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hi.

I'm writing a program, and I need to send confidential data through the
network, so I decided to use encryption, using the
System.Security.Cryptography namespace.

I'm using the sockets for the network communications, and the program
first does a key exchange, with the asymetric cipher classes, to get a new
key for the symmetric cipher. My problem is, that although I have checked
that the two points get to the same key and initialization vector, when
the sender sends the data, its ok, but the receiver gets blocked. I am
using blocking sockets, so I am aware that if the socket does not have
received data, it blocks until it does. But I know that it does receive
the data, and still it blocks, not the NetworkStream, but the CryptoStream
used to decrypt the data. I have been trying many things, using the
StreamReader and StreamWriter like in the documentation examples, but
doesn't work.

I need help, please. It's been 2 full days trying, please help.

Alejandro.

Here are some lines of the code:

This is the receiver code (where it blocks, in the Read function):

string mensaje;
NetworkStream stream = clienteTcp.GetStream();
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateDecryptor(tdesClave ,tdesIV),

CryptoStreamMode.Read);
// Búfer de 8Kb
byte[] datos = new byte[8192];
int bytes;
int intentos = 25;
// Detectar si hay datos
while(intentos > 0)
{
if (stream.DataAvailable)
break;
intentos--;
System.Threading.Thread.Sleep(200);
}
// Si no hay datos salir
if (!stream.DataAvailable)
return String.Empty;
// Leer mensaje
bytes = crStream.Read(datos,0,datos.Length);
// Pasar a string
mensaje = System.Text.Encoding.Unicode.GetString(datos,0,byt es);
This is the sender code:

NetworkStream stream = new NetworkStream(clienteTcp);
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateEncryptor(tdesClave ,tdesIV),
CryptoStreamMode.Write);
// Convertir el string a una matriz de bytes
byte[] datos = System.Text.Encoding.Unicode.GetBytes(mensaje);
// Transmitir mensaje
crStream.Write(datos,0,datos.Length);
crStream.Flush();


Nov 16 '05 #2
Thank you Nicholas.
The receiver routine I wrote for receiving plain data is almost the same,
only that it calls Read in the NetworkStream object instead of the
CryptoStream, with the same length of 8192 bytes, and it doesn't block, and
returns the number of bytes actually read.

Is the CryptoStream different to the NetworkStream in this matter?
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> escribió
en el mensaje news:%2****************@TK2MSFTNGP10.phx.gbl...
Alejandro,

It looks like you are trying to read too much data. You are issuing a
call to the Read method on the socket class passing in a length of 8192
bytes. If the sender does not send 8192 bytes, the call to Read is going
to block until it gets 8192 bytes.

There are two ways of handling this. The first is to mark your message
with an identifier which indicates that the message has completed
transmission. This would require you to read byte-by-byte, which is not a
good thing.

The second is to actually send the length of the message before you
send the message yourself. This way, you can issue a call to the Read
method and know you are not asking for more data than is on the line.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Alejandro Castañaza" <da*****************@itelgua.com> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hi.

I'm writing a program, and I need to send confidential data through the
network, so I decided to use encryption, using the
System.Security.Cryptography namespace.

I'm using the sockets for the network communications, and the program
first does a key exchange, with the asymetric cipher classes, to get a
new key for the symmetric cipher. My problem is, that although I have
checked that the two points get to the same key and initialization
vector, when the sender sends the data, its ok, but the receiver gets
blocked. I am using blocking sockets, so I am aware that if the socket
does not have received data, it blocks until it does. But I know that it
does receive the data, and still it blocks, not the NetworkStream, but
the CryptoStream used to decrypt the data. I have been trying many
things, using the StreamReader and StreamWriter like in the documentation
examples, but doesn't work.

I need help, please. It's been 2 full days trying, please help.

Alejandro.

Here are some lines of the code:

This is the receiver code (where it blocks, in the Read function):

string mensaje;
NetworkStream stream = clienteTcp.GetStream();
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateDecryptor(tdesClave ,tdesIV),

CryptoStreamMode.Read);
// Búfer de 8Kb
byte[] datos = new byte[8192];
int bytes;
int intentos = 25;
// Detectar si hay datos
while(intentos > 0)
{
if (stream.DataAvailable)
break;
intentos--;
System.Threading.Thread.Sleep(200);
}
// Si no hay datos salir
if (!stream.DataAvailable)
return String.Empty;
// Leer mensaje
bytes = crStream.Read(datos,0,datos.Length);
// Pasar a string
mensaje = System.Text.Encoding.Unicode.GetString(datos,0,byt es);
This is the sender code:

NetworkStream stream = new NetworkStream(clienteTcp);
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateEncryptor(tdesClave ,tdesIV),
CryptoStreamMode.Write);
// Convertir el string a una matriz de bytes
byte[] datos = System.Text.Encoding.Unicode.GetBytes(mensaje);
// Transmitir mensaje
crStream.Write(datos,0,datos.Length);
crStream.Flush();



Nov 16 '05 #3
By the way...
Is there a method to convert an int to an array of bytes?

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> escribió
en el mensaje news:%2****************@TK2MSFTNGP10.phx.gbl...
Alejandro,

It looks like you are trying to read too much data. You are issuing a
call to the Read method on the socket class passing in a length of 8192
bytes. If the sender does not send 8192 bytes, the call to Read is going
to block until it gets 8192 bytes.

There are two ways of handling this. The first is to mark your message
with an identifier which indicates that the message has completed
transmission. This would require you to read byte-by-byte, which is not a
good thing.

The second is to actually send the length of the message before you
send the message yourself. This way, you can issue a call to the Read
method and know you are not asking for more data than is on the line.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Alejandro Castañaza" <da*****************@itelgua.com> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
Hi.

I'm writing a program, and I need to send confidential data through the
network, so I decided to use encryption, using the
System.Security.Cryptography namespace.

I'm using the sockets for the network communications, and the program
first does a key exchange, with the asymetric cipher classes, to get a
new key for the symmetric cipher. My problem is, that although I have
checked that the two points get to the same key and initialization
vector, when the sender sends the data, its ok, but the receiver gets
blocked. I am using blocking sockets, so I am aware that if the socket
does not have received data, it blocks until it does. But I know that it
does receive the data, and still it blocks, not the NetworkStream, but
the CryptoStream used to decrypt the data. I have been trying many
things, using the StreamReader and StreamWriter like in the documentation
examples, but doesn't work.

I need help, please. It's been 2 full days trying, please help.

Alejandro.

Here are some lines of the code:

This is the receiver code (where it blocks, in the Read function):

string mensaje;
NetworkStream stream = clienteTcp.GetStream();
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateDecryptor(tdesClave ,tdesIV),

CryptoStreamMode.Read);
// Búfer de 8Kb
byte[] datos = new byte[8192];
int bytes;
int intentos = 25;
// Detectar si hay datos
while(intentos > 0)
{
if (stream.DataAvailable)
break;
intentos--;
System.Threading.Thread.Sleep(200);
}
// Si no hay datos salir
if (!stream.DataAvailable)
return String.Empty;
// Leer mensaje
bytes = crStream.Read(datos,0,datos.Length);
// Pasar a string
mensaje = System.Text.Encoding.Unicode.GetString(datos,0,byt es);
This is the sender code:

NetworkStream stream = new NetworkStream(clienteTcp);
// Crear el stream criptográfico
CryptoStream crStream = new
CryptoStream(stream,TDES.CreateEncryptor(tdesClave ,tdesIV),
CryptoStreamMode.Write);
// Convertir el string a una matriz de bytes
byte[] datos = System.Text.Encoding.Unicode.GetBytes(mensaje);
// Transmitir mensaje
crStream.Write(datos,0,datos.Length);
crStream.Flush();



Nov 16 '05 #4
Alejandro Castañaza <da*****************@itelgua.com> wrote:
By the way...
Is there a method to convert an int to an array of bytes?


Look at BitConverter.GetBytes.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Thank you. I was writing my own method already. This is what I like about
..NET! you don't have to waste time writing this kind of things!

"Jon Skeet [C# MVP]" <sk***@pobox.com> escribió en el mensaje
news:MP************************@msnews.microsoft.c om...
Alejandro Castañaza <da*****************@itelgua.com> wrote:
By the way...
Is there a method to convert an int to an array of bytes?


Look at BitConverter.GetBytes.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
I tried your second sugestion, sending first the length of the message, then
call Read with that number, but it still blocks. It reads the length but
the call to cryptoStream.Read still blocks. Please help!
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> escribió
en el mensaje news:%2****************@TK2MSFTNGP10.phx.gbl...
Alejandro,

It looks like you are trying to read too much data. You are issuing a
call to the Read method on the socket class passing in a length of 8192
bytes. If the sender does not send 8192 bytes, the call to Read is going
to block until it gets 8192 bytes.

There are two ways of handling this. The first is to mark your message
with an identifier which indicates that the message has completed
transmission. This would require you to read byte-by-byte, which is not a
good thing.

The second is to actually send the length of the message before you
send the message yourself. This way, you can issue a call to the Read
method and know you are not asking for more data than is on the line.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com


Nov 16 '05 #7
At last! Solved the problem.

I used the cryptostream object in the receiver to write to a memorystream
instead of reading the networkstream, and it worked.

Seems like the cryptostream won't read from a networkstream. A .net bug?

Thank you all very much for your help.

Alejandro.

"Alejandro Castañaza" <da*****************@itelgua.com> escribió en el
mensaje news:OW****************@TK2MSFTNGP15.phx.gbl...
I tried your second sugestion, sending first the length of the message,
then call Read with that number, but it still blocks. It reads the length
but the call to cryptoStream.Read still blocks. Please help!
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com>
escribió en el mensaje news:%2****************@TK2MSFTNGP10.phx.gbl...
Alejandro,

It looks like you are trying to read too much data. You are issuing a
call to the Read method on the socket class passing in a length of 8192
bytes. If the sender does not send 8192 bytes, the call to Read is going
to block until it gets 8192 bytes.

There are two ways of handling this. The first is to mark your
message with an identifier which indicates that the message has completed
transmission. This would require you to read byte-by-byte, which is not
a good thing.

The second is to actually send the length of the message before you
send the message yourself. This way, you can issue a call to the Read
method and know you are not asking for more data than is on the line.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

Nov 16 '05 #8
Alejandro Castañaza <da*****************@itelgua.com> wrote:
At last! Solved the problem.

I used the cryptostream object in the receiver to write to a memorystream
instead of reading the networkstream, and it worked.

Seems like the cryptostream won't read from a networkstream. A .net bug?


Unlikely. I use CryptoStreams every day over NetworkStreams.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

By the way, in your original code I notice you aren't calling
FlushFinalBlock on the CryptoStream - are you doing that in your real
code?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
Jon
I made many changes to the original code after I posted, because I was still
trying to make it work. Then I added the call to FlushFinalBlock, but the
Read call still blocked. Then I used the streamReader, ReadToEnd and
blocked. Then, after looking some example code for encryption, I tried the
solution I wrote earlier, using the cryptostream object to write to a temp
memorystream, and reading the plain text from it. Its working that way.

I didn't mean to say for sure it is a bug. Since the first message I asked
for help, because I thought maybe I was missing something (like the call to
flushfinalblock) or was doing something wrong.

I havent tried, but after I finally made it work, I thought that the problem
was because encryption always expand a little the original block of data,
and that was why I was having trouble with it. That is the reason to call
FlushFinalBlock or close the cryptostream, right? so it can finish the
encryption process and send the last block of encrypted data. So maybe I
have to try reading the networkstream using the cryptostream with this
concept in mind. But I'll do it later. Its working now, and I have so much
to do still about that program.

I appreciate your comments.

Alejandro.
"Jon Skeet [C# MVP]" <sk***@pobox.com> escribió en el mensaje
news:MP************************@msnews.microsoft.c om...
Alejandro Castañaza <da*****************@itelgua.com> wrote:
At last! Solved the problem.

I used the cryptostream object in the receiver to write to a memorystream
instead of reading the networkstream, and it worked.

Seems like the cryptostream won't read from a networkstream. A .net bug?


Unlikely. I use CryptoStreams every day over NetworkStreams.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

By the way, in your original code I notice you aren't calling
FlushFinalBlock on the CryptoStream - are you doing that in your real
code?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
Alejandro Castañaza <da*****************@itelgua.com> wrote:
I made many changes to the original code after I posted, because I was still
trying to make it work. Then I added the call to FlushFinalBlock, but the
Read call still blocked. Then I used the streamReader, ReadToEnd and
blocked. Then, after looking some example code for encryption, I tried the
solution I wrote earlier, using the cryptostream object to write to a temp
memorystream, and reading the plain text from it. Its working that way.

I didn't mean to say for sure it is a bug. Since the first message I asked
for help, because I thought maybe I was missing something (like the call to
flushfinalblock) or was doing something wrong.

I havent tried, but after I finally made it work, I thought that the problem
was because encryption always expand a little the original block of data,
and that was why I was having trouble with it. That is the reason to call
FlushFinalBlock or close the cryptostream, right? so it can finish the
encryption process and send the last block of encrypted data.
Not only that - but so it can then tell the stream that it's finished,
so that things like ReadToEnd will complete. If you leave the stream
open, things like ReadToEnd won't know whether there might be some more
data to come or not.
So maybe I have to try reading the networkstream using the
cryptostream with this concept in mind. But I'll do it later. Its
working now, and I have so much to do still about that program.


Fair enough. If you do find out what was wrong, please report back to
the group :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

38
by: Tim Tyler | last post by:
Here's what this morning's security advisory read here: ``In the last 3 months we have noticed an marked increase in the number of web-server attacks and successful compromise on our network....
1
by: Mansoor Azam | last post by:
We connect to a SQL 6.5 server (IP for example 202.64.213.11) on WIN NT using ODBC DSN and / or SQL Client (DB-LIB). Everthing was working fine then the some XP client machines (192.168.0.1 and...
0
by: ZR | last post by:
I am writing two applications which needs to (among other things) communicate through network, so one of them is a client and the other one is a server. I have used asynchronous socket examples...
1
by: muthu | last post by:
Hi, I have two web applications running on my machine.The application is developed using asp.net 1.1 and vb.net.When i try to run both the applications in the same browsers, i get the following...
8
by: Mike Owen | last post by:
Hi, I am using the following code to send email on a Windows 2003 Web Server: Imports System.Net.Mail ........ Dim msgmail As New MailMessage msgmail.To.Add(New...
1
by: =?Utf-8?B?ZGF2aWQ=?= | last post by:
Hi, everybody here. I am implementing data encryption/decryption, and try to use System.Security.Cryptography.TripleDESCryptoServiceProvider. But I can not find it in MS Visual Studio when I...
2
by: John Nagle | last post by:
Trying to build M2Crypto on a dedicated server running Red Hat Fedora Core 6. I'm trying to do this right, without manual patching. The error message I'm getting during build is: python...
1
by: Eric Simmons | last post by:
Hello, I am trying to run a .NET 2.0 application that I developed and I am getting the following error: Key not valid for use in specified state I am attempting to retrieve the...
1
by: Napcrisis | last post by:
Hi guys i need to know if its possible to use visual c++ and make use of .net cryptography to encrypt files using the cryptography algorithms .net has to offer. cuz i have been searching around and...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.