r1cki
r1cki

Reputation: 117

.Net AES Padding Problem

im currently having a problem with the padding when decrypting a utf8 encoded string.

string length is not a multiple of 16, i use PKCS7 paddingmode

of course i do use the

cs.FlushFinalBlock()

statement.

whats happing is, after decrypting, the stream wont hold the last block. but when is use no paddingmode only while decrypting, the last block is there(with paddingbytes)

i have no clue whats wrong ;)

heres a bit code(vb.net im sry :D)

encryption

            Dim rawPlaintext As Byte() = utf8.GetBytes(text)
            aes.Padding = PaddingMode.PKCS7
            Using ms As New MemoryStream()
                Using cs As New CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)
                    cs.Write(rawPlaintext, 0, rawPlaintext.Length)
                    cs.FlushFinalBlock()
                    ms.Position = 0
                End Using
                Return ms
            End Using

decryption

        aes.Padding = PaddingMode.PKCS7
        
        Using ms As New MemoryStream()
            Using cs As New CryptoStream(ms, aes.CreateDecryptor(key, iv),

CryptoStreamMode.Write)

                ciphertext.CopyTo(cs)
                ciphertext.Close()
                ms.Position = 0
            End Using
            Return ms            
        End Using

hope u guys can help ;)

thanks

Upvotes: 1

Views: 1163

Answers (1)

Mormegil
Mormegil

Reputation: 8071

I can see two problems with your code: The first is probably minor: I don’t think it is a good practice to pass around a disposed MemoryStream – do not return the MemoryStream, return only the contained array (use ms.ToArray()).

The second is worse: you do not need to call cs.FlushFinalBlock() explicitly, it is called automatically on Dispose (when leaving the Using block of the CryptoStream). However, in the second case you do not call it, and you reset position of the output stream while the decrypting CryptoStream has not finished yet. It means that only after changing the stream position, the CryptoStream gets to flushing the final block. You can work around that by adding cs.FlushFinalBlock() before ms.Position = 0 in the decryption code.

But, IMHO just remove the stream seek completely (possibly with FlushFinalBlock in the encryption code), and you should be fine, too.

Upvotes: 2

Related Questions