views:

667

answers:

4

Good day :)

I'm pretty new to both C++ and Block Cipher encryption, and I am currently in the process of writing a decryption function for AES (16 byte seed / 16 byte blocks). All is going well, but my total data size is not always a multiple of my block size. I'm wondering what the best way to handle left-over data at the end of my data.

I'm using Crypto++ for the AES library.

The ProcessBlock() function takes an Input and Output char array. I'm assuming it is expecting them to be at least big enough as the block size.

TL:DR;

What would be the best way to process all 16 byte blocks in a block cipher, and then also process the leftover data?

A: 

What you want is a padding system.

Check out this CodeProject article on Crypto++:

When a message is not a multiple of the cipher's block size, ECB or CBC mode messages must be padded. The method and values of padding are a source of problem with respect to interoperability between Cryptographic libraries and APIs. As Garth Lancaster points out, if you're not aware of the particulars of padding, use the StreamTransformationFilter. In this case, the Crypto++ filter will pad for you.

amdfan
A: 

There's a PKCS standard for what's called "padding"

See the wikipedia page, but it amounts to padding with one of:

 01
 02 02
 03 03 03
 04 04 04 04
 05 05 05 05 05

This way you know during decryption where the original message ends...

Purfideas
A: 

Thanks for you answers,

However, that documentation is referring to a member 'StreamTransformationFilter', which just does not seem to exist here. I do have a 'StreamTransformation' member, but it seems to be quite different.

My cryptopp version is the latest btw (5.5.2)

edit:

And yes, I have filters.h included.

+1  A: 

It's more than just padding - you need a Mode of Operation. The Good Math, Bad Math blog is writing up an excellent series on what they are and how to use them here. Also see the wikipedia entry. One thing that's really, really important: Never, ever use ECB (Electronic Code Book) mode - where you encrypt each block independently. It's the obvious way to do it, but it provides appallingly poor security.

Ideally, though, you shouldn't even have to do this yourself. Your crypto library should provide it. If it doesn't, I'd suggest changing to something else. like OpenSSL.

Nick Johnson