473,404 Members | 2,137 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,404 software developers and data experts.

Rijndael CryptoStream, NetworkStream, and Padding

A client creates a connection to the server using the TCPListener/Client
classes and transfers data via a NetworkStream. When the client connects,
the server creates a process and redirects its StandardOut to traverse back
over the network to the client. I want to encrypt this data and the code I
have is below. However, occasionally during processing, I receive an
exception stating the PKCS7 padding is invalid and cannot be removed. I have
searched high and low for this. While I have found some interesting
discussions, I have yet to find a clear answer. Please help. Thanks!

'// Server code: Called after receiving a command from the client.
'// Encrypts data and returns it
Private Sub OnCompletedReadStdOut(ByVal ar As IAsyncResult)

If ar Is Nothing Then Return

Try
Dim intBytesRead As Integer = StreamStdOut.EndRead(ar)

If intBytesRead > 0 Then
Dim s As String = Encoding.ASCII.GetString(BufferStdOut,
0, intBytesRead)

If s <> strLastCommand Then
'// Create a memory stream and encrypt data to it
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms,
aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write)

'BufferStdOut is dimensioned to 204800.
'No need for this size. 1024 would suffice but the
problem
'happens less frequently the larger the buffer.
cs.Write(BufferStdOut, 0, intBytesRead)
cs.FlushFinalBlock() 'error occurs here **

'// get the encrypted data to send
Dim bytData(ms.Length) As Byte
ms.Position = 0
intBytesRead = ms.Read(bytData, 0, ms.Length)
cs.Close()

Stream.Write(bytData, 0, bytData.Length)

bytData = Nothing
cs.Clear()
cs = Nothing
ms = Nothing
End If

'// reinitialize the asyncronous callback
StreamStdOut.BeginRead(BufferStdOut, 0,
BufferStdOut.Length, CallBackStdOut, Nothing)
End If

Catch ex As Exception
'// Return error info
End Try
End Sub

'// Client code: Called after receiving data from the server.
'// Decrypts and displays data
Private Sub OnCompletedRead(ByVal ar As IAsyncResult)
If ar Is Nothing Then Shutdown()

Try
Dim intBytesRead As Integer = Stream.EndRead(ar)

If intBytesRead > 0 Then
'// Decrypt data
Try
'// Put buffer into memory and create a decryptor
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms,
aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Write)

'bytBuffer is the same size as BufferStdOut (mentioned
above)
cs.Write(bytBuffer, 0, intBytesRead - 1)
cs.FlushFinalBlock() 'error occurs here **

'// decrypt the data
Dim bytData(ms.Length) As Byte
ms.Position = 0
intBytesRead = ms.Read(bytData, 0, ms.Length)
cs.Close()

If intBytesRead > 0 Then
'// Translate the data to the string and display
Dim s As String = Encoding.ASCII.GetString(bytData,
0, intBytesRead)

Console.Write(s)
End If

bytData = Nothing
cs.Clear()
cs = Nothing
ms = Nothing
Catch ex As Exception
'// Return Error Info
Console.WriteLine(ex.ToString)
End Try

'// Reinitialize the callback
Stream.BeginRead(bytBuffer, 0, bytBuffer.Length, callback,
Nothing)
Else
'// The connection was terminated by the server
Shutdown()
End If
Catch ex As Exception
'// The connection was terminated by the server
Shutdown()
End Try
End Sub
Nov 19 '05 #1
1 6581
"Nicholas Holder" <nr******@no-spam-hotmail.com> wrote in message news:<#W**************@tk2msftngp13.phx.gbl>...
A client creates a connection to the server using the TCPListener/Client
classes and transfers data via a NetworkStream. When the client connects,
the server creates a process and redirects its StandardOut to traverse back
over the network to the client. I want to encrypt this data and the code I
have is below. However, occasionally during processing, I receive an
exception stating the PKCS7 padding is invalid and cannot be removed. I have
searched high and low for this. While I have found some interesting
discussions, I have yet to find a clear answer. Please help. Thanks!

Nicholas -

Most likely you are not receiving all of the encrypted data before
feeding it into the decryptor. With TCP there is no guarantee that all
of the data sent from a single Write() will be read by a single
Read(). You must account for that in your client code.

Since you already know the size of the data being sent, my
recommendation would be to send the size value before the actual data.
On the client side, read the size value, then loop on the Read()
methods until all of the data has been read. Then you know you have
all of the data to feed into the decryptor.

Hope this helps solve your problem.

Rich Blum
Author of "C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
Nov 19 '05 #2

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

Similar topics

2
by: Ayende Rahien | last post by:
I've a problem in my code using NetworkStream. I've a server which listen to a port, and then Read() from it, and a client that send data. My NetworkStream is wrapped in a CryptoStream, and my...
1
by: Casey Watson | last post by:
Hi :) I'm having some major trouble with an XML Client/Server application that I am writing. I am using NetworkStream with CryptoStream to Read and Write XML between computers. Now, whenever I...
5
by: William Stacey [MVP] | last post by:
The Decypt2() method below does not work. It completes, but does not do the right thing. The first transform request returns 0 bytes. The first Decypt() method works as we work on a stream...
4
by: Mantorok | last post by:
Hi I have a couple of encryption methods but when I call decrypt I get the string back but with a load \0 escape characters on the end? Any idea why? It is actually causing problems in some...
5
by: ~~~ .NET Ed ~~~ | last post by:
Anybody has any idea why this simple thing is not working? I pass a text file as input to encrypt it, then pass the encrypted version to the same function and get some garbled data not at all...
7
by: semedao | last post by:
Hi, I am using cryptostream on both sides on tcp connection that pass data. I am also use asyc socket , so , the data that recieved in the callback method not always have the length of the buffer...
0
by: Vayse | last post by:
I need to encrypt some strings in serveral programs I have. So I grabbed some code from the MS help. I wrote an app that would help me generate the encrypted strings. Its s form with 4 text boxes...
3
by: KBS Developer | last post by:
Hi, I can encrypt without any problem but while decrypting I got junk. I've read the other thread about getting junk but that is not my case. Here is the sample code: private Rijndael...
1
by: MilesDyson88588 | last post by:
This is driving me insane. Ive checked every sample and cant see anything happening differently. I'm sending the file over a network so the key and IV bytes are sent with the file to be used to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: 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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.