encryption padding problem with RijndaelManaged

G

Guest

I thought the following code worked for me until I looked closer.
My first clue came when I tried to decrypt the file, and got a
CryptographicException saying:
Padding is invalid and cannot be removed.

I looked at the file sizes, and the encrypted file is a
little smaller than the source file,
the exact opposite of what I expected:
WindowsUpdate.log (a copy of the original) is 1,827,175 bytes
WindowsUpdate.txt is 1,827,168 bytes

What went wrong?

Thanks,
Jon

Sub Main()
ec = New EmpCipher()
crypt("C:\0JQJ\WindowsUpdate.log", "C:\0JQJ\WindowsUpdate.txt")
End Sub

Sub crypt(ByVal source As String, ByVal dest As String)
'read in a clear file to an array of bytes
Dim inFile As FileStream = New FileStream(source, FileMode.Open,
FileAccess.Read)
Dim L As Int32 = inFile.Length
Dim b(L) As Byte
inFile.Read(b, 0, L)

'get encrypted stream from byte array
Dim m As MemoryStream = ec.c3(b)
m.Seek(0, SeekOrigin.Begin)
L = m.Length

'write the encrypted stream to a file
Dim buf(L - 1) As Byte
m.Read(buf, 0, L)
Dim fs As FileStream = New FileStream(dest, FileMode.Create,
FileAccess.Write)
fs.Write(buf, 0, L)
fs.Close()
End Sub

'from the EmpCipher class, intended to encrypt any byte array, not just files
Public Function c3(ByVal b() As Byte) As MemoryStream
Dim e As ICryptoTransform = alg.CreateEncryptor
Dim m As MemoryStream = New MemoryStream()
Dim c As CryptoStream = New CryptoStream(m, e, CryptoStreamMode.Write)
c.Write(b, 0, b.Length)
Return m
End Function
 
J

JR

From the Help:

"You should always explicitly close your CryptoStream object after you are
done using it by calling the Close method. Doing so flushes the stream and
causes all remain blocks of data to be processed by the CryptoStream
object."

This could be the reason for your bug.

JR
 
J

JR

From the Help:

"You should always explicitly close your CryptoStream object after you are
done using it by calling the Close method. Doing so flushes the stream and
causes all remain blocks of data to be processed by the CryptoStream
object."

This could be the reason for your bug.

JR
 
G

Guest

"You should always explicitly close your CryptoStream object after you are
This could be the reason for your bug.
That is very probably it. Thank you very much
 
J

JR

From the Help:

"You should always explicitly close your CryptoStream object after you are
done using it by calling the Close method. Doing so flushes the stream and
causes all remain blocks of data to be processed by the CryptoStream
object."

This could be the reason for your bug.

JR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top