Polarssl AES counter mode example

1.5k views Asked by At

I am looking for an example for Polarssl AES counter mode. Couldn't find it anywhere.

Documentation is difficult to understand for a beginner like me. It is defined in polarssl as

int     aes_crypt_ctr (aes_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16], const unsigned char *input, unsigned char *output)

I wrote like this

aes_context aes;

unsigned char key[32];
unsigned char iv[16];

unsigned char input [128]="Hello";
unsigned char output[128];

size_t input_len = 40;
size_t output_len = 0;

aes_setkey_enc(&aes, key, 128);


aes_crypt_ctr (&aes, 64, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16], input, output);

I couldnt understand certain parameters in the call to encryption. I am looking for a minimal working example.

1

There are 1 answers

0
Paul On

Counter mode (CTR) is different from modes like CBC, because it can work on non-complete blocks. If you use CBC on a non-complete block it is often padded and then the encryption stream has for all purposes ended. You cannot add data on the end.

CTR is more meant and implemented as a stream cipher within PolarSSL, and allows you to tack additional data on the end. As a result it needs to now 'where' it is inside the current block (nc_off).

So what you should do is:

  1. Rename iv to nonce_counter for clarity.
  2. Add size_t nc_offset = 0; to the top.
  3. add unsigned char stream_block[16]; to the top.
  4. Put a random value in nonce_counter (This is your nonce + counter within the nonce) Use something like CTR-DRBG. You can check this article on adding a random generator to your code.
  5. If you want to do a single call: ret = aes_crypt_ctr(&aes, input_len, &nc_off, nonce_counter, stream_block, input, output);

Note: At the end of your call to aes_crypt_ctr(), nc_off will be at 40 % 16 = 8, indicating that there are still 8 bytes left in stream_block that aes_crypt_ctr() can use if you decide to add extra data to the stream.