# AES plaintext is smaller than 128 bits - how to expand?

We are currently developing a little AES implementation in a crypto-course at university.

As far as I know, AES uses a 128 bit block length, so all data that will be encrypted gets split up into blocks of 128 bits (16 bytes) into a 2d-array (or 1d in implementation) with 4 × 4 fields.

I was wondering and didn't find out what to do if the entered string to encrypt is not 128 bits long? The question is going further by thinking that there will never be exactly n × 128 bits of data to encrypt.

For a smaller key given by the user (e.g. "test") I know there is a key expansion algorithm defined.

But what should be done for data that is less than 128 bits?

-
Padding is what you are looking for. –  mikeazo Apr 25 '13 at 14:53
looks good as it is the answer - maybe you should add it as a answer to this question so I can check it :-) –  Stefan Apr 25 '13 at 15:07

A block cipher is an invertible transformation that maps an $n$ bit block of bits to an $n$ bit block of bits, under the control of a key (and where $n=128$ in the case of AES)

Now, we most often need to do things other than mapping blocks of $n$ bits; how we do that is using the block cipher within a Mode of Operation. A mode of operation is just a way to use the block cipher to solve some problem we want solving.

There have been quite a number of modes of operations defined; the most common ones are CBC and CTR (counter). The majority of them (including CBC and CTR) solve the problem 'how do I encrypt an arbitrarily sized message'.

As for 'how to handle odd sized messages', CBC and CTR take two different approaches.

With standard CBC, we assume that the message is always a multiple of $n$ bits; so, what we do is add padding to the message before we do that actual CBC-mode transformation. This padding fills out the message to a multiple of $n$ bits; this padding is designed so that the decryptor can easily remove it after decryption. Note: I said standard CBC because there are fancier ways to avoid this padding within CBC mode; they involve handling the last partial block as a special case.

With CTR mode, it doesn't assume that the message is a multiple of $n$ bits at all. It doesn't actually send the message through the block cipher; instead, it generates a keystream by sending an incrementing pattern through the block cipher (so the first $n$ bits of the keystream may be generated by encrypting the value 1, and the second $n$ bits of the keystream may be generated by encryption the value 2, etc). One we have such a key stream, having the message not being a multiple of $n$ bits is not an issue; we just discard the parts of the keystream we don't need to encrypt.

-

One common way for AES in CBC padding is to pad number $k$ if you are $k$ bytes short of 16 bytes $k$ times (e.g if you have 9 bytes you should pad 07 07 07 07 07 07 07). Note that you have to pad 16 '10' if you have 16 bytes at the beginning.

-