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.
// ...
}
```