1
$\begingroup$

I referred to the explanation of encryption mode from Wikipedia, but I'm confused now, and I went to find some books about Cryptography, but it didn't solve my confusion.

The CTR mode uses Counter to participate in encryption.

But in Wikipedia, the encryption process is as follows:

It can be seen that both Nonce and Counter are encrypted by the block cipher encryption, so how are Nonce and Counter combined?

Does the following code I provide fully comply with the interpretation of CTR mode?

typedef struct {
    uint8_t iv[16];
    uint8_t key[32];
} cipher_ctx;

#define BLOCK_LEN 16

void cipher(uint8_t *, uint8_t *);

void ctr_xcrypt(cipher_ctx *ctx, uint8_t *buf, size_t size)
{
    uint8_t counter[16];
    uint32_t block_count = size / BLOCK_LEN;

    memset(counter, 0, sizeof(counter));
    memcpy(counter, ctx->iv, 8);

    cipher(counter, ctx->key);
    for(int x = 0; x < 16; ++x) {
        buf[x] ^= counter[x];
    }

    // Perform the Counter plus one operation.
    // ...
}
```
$\endgroup$

1 Answer 1

1
$\begingroup$

I understand your confusion about the figure from Wikipedia.

There is simply a nonce which is public. This nonce is then incremented by adding 1 to it at each iteration, as in the code. So I suppose you could say the combination is to add a counter which goes $0,1,2,\ldots$ to a nonce, via integer addition.

Let $X_i$ be the plaintext and $Y_i$ the ciphertext with $Z$ the initial value of the counter, i.e., the nonce. Then we have

  1. $Y_1=E_K(Z)\oplus X_1$
  2. $Y_2=E_K(Z+1)\oplus X_2$
  3. $Y_1=E_K(Z+2)\oplus X_3$

and so on.

The + indicates integer addition, i.e., incrementing the counter.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.