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.
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:
iv
tononce_counter
for clarity.size_t nc_offset = 0;
to the top.unsigned char stream_block[16];
to the top.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 instream_block
thataes_crypt_ctr()
can use if you decide to add extra data to the stream.