CTR is also an encryption mode, just use a counter as IV, and use IV’s cipher xor plain data by bytes.
Cause x ^ y ^ y = x, we can see that the encrypt and decrypt function are the same. And as there is no feedback in encrpytion, jut with the AES key and the counter we can decrypt any block of cipher.
With this mode we can encrypt any length of plain data, and the counter is used as IV.
Let’s get into the Open SSL source code:
void AES_ctr128_encrypt(const unsigned char *in, unsigned char *out, const unsigned long length, const AES_KEY *key, unsigned char ivec[AES_BLOCK_SIZE], unsigned char ecount_buf[AES_BLOCK_SIZE], unsigned int *num) { unsigned int n; unsigned long l=length;
assert(in && out && key && counter && num); assert(*num < AES_BLOCK_SIZE);
n = *num;
while (l--) { if (n == 0) { AES_encrypt(ivec, ecount_buf, key); AES_ctr128_inc(ivec); } *(out++) = *(in++) ^ ecount_buf[n]; n = (n+1) % AES_BLOCK_SIZE; }
*num=n; } |
The parameter Ivec is the buffer containing the counter. We can see that the counter is restored in a 16 bytes buffer. It’s both for in and out.
The parameter Num indicates which byte to begin with when the block is to be encrypted.
Both num and ecount_buf must be initialized with zeros before the first call to AES_ctr128_encrypt().
By the way, the function AES_ctr128_inc()is wroth reading, it provides a simple way for big number calculation.
#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) # define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00) # define GETU32(p) SWAP(*((u32 *)(p))) # define PUTU32(ct, st) { *((u32 *)(ct)) = SWAP((st)); } #else # define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3])) # define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); } #endif
/* NOTE: the IV/counter CTR mode is big-endian. The rest of the AES code * is endian-neutral. */
/* increment counter (128-bit int) by 1 */ static void AES_ctr128_inc(unsigned char *counter) { unsigned long c;
/* Grab bottom dword of counter and increment */ c = GETU32(counter + 12); c++; c &= 0xFFFFFFFF; PUTU32(counter + 12, c);
/* if no overflow, we're done */ if (c) return;
/* Grab 1st dword of counter and increment */ c = GETU32(counter + 8); c++; c &= 0xFFFFFFFF; PUTU32(counter + 8, c);
/* if no overflow, we're done */ if (c) return;
/* Grab 2nd dword of counter and increment */ c = GETU32(counter + 4); c++; c &= 0xFFFFFFFF; PUTU32(counter + 4, c);
/* if no overflow, we're done */ if (c) return;
/* Grab top dword of counter and increment */ c = GETU32(counter + 0); c++; c &= 0xFFFFFFFF; PUTU32(counter + 0, c); } |
Well the macro GETU32 can be used as ntohl(). The function AES_ctr128_inc() calculates the big number part by part. Divided and conquer.