nettle: CTR

1 
1 6.3.2 Counter mode
1 ------------------
1 
1 Counter mode (CTR) uses the block cipher as a keyed pseudo-random
1 generator.  The output of the generator is XORed with the data to be
1 encrypted.  It can be understood as a way to transform a block cipher to
1 a stream cipher.
1 
1    The message is divided into ‘n’ blocks ‘M_1’,... ‘M_n’, where ‘M_n’
1 is of size ‘m’ which may be smaller than the block size.  Except for the
1 last block, all the message blocks must be of size equal to the cipher’s
1 block size.
1 
1    If ‘E_k’ is the encryption function of a block cipher, ‘IC’ is the
1 initial counter, then the ‘n’ plaintext blocks are transformed into ‘n’
1 ciphertext blocks ‘C_1’,... ‘C_n’ as follows:
1 
1      C_1 = E_k(IC) XOR M_1
1      C_2 = E_k(IC + 1) XOR M_2
1 
1      ...
1 
1      C_(n-1) = E_k(IC + n - 2) XOR M_(n-1)
1      C_n = E_k(IC + n - 1) [1..m] XOR M_n
1 
1    The IC is the initial value for the counter, it plays a similar rôle
1 as the IV for CBC.  When adding, ‘IC + x’, IC is interpreted as an
1 integer, in network byte order.  For the last block, ‘E_k(IC + n - 1)
1 [1..m]’ means that the cipher output is truncated to ‘m’ bytes.
1 
1  -- Function: void ctr_crypt (const void *CTX, nettle_cipher_func *F,
1           size_t BLOCK_SIZE, uint8_t *CTR, size_t LENGTH, uint8_t *DST,
1           const uint8_t *SRC)
1 
1      Applies the encryption function F in CTR mode.  Note that for CTR
1      mode, encryption and decryption is the same operation, and hence F
1      should always be the encryption function for the underlying block
1      cipher.
1 
1      When a message is encrypted using a sequence of calls to
1      ‘ctr_crypt’, all but the last call _must_ use a length that is a
1      multiple of the block size.
1 
1    Like for CBC, there are also a couple of helper macros.
1 
1  -- Macro: CTR_CTX (CONTEXT_TYPE, BLOCK_SIZE)
1      Expands to
1           {
1              context_type ctx;
1              uint8_t ctr[block_size];
1           }
1 
1  -- Macro: CTR_SET_COUNTER (CTX, IV)
1      First argument is a pointer to a context struct as defined by
1      ‘CTR_CTX’, and the second is a pointer to an initial counter that
1      is copied into that context.
1 
1  -- Macro: CTR_CRYPT (CTX, F, LENGTH, DST, SRC)
1      A simpler way to invoke ‘ctr_crypt’.  The first argument is a
1      pointer to a context struct as defined by ‘CTR_CTX’, and the second
1      argument is an encryption function following Nettle’s conventions.
1      The last three arguments define the source and destination area for
1      the operation.
1