From 23ff272f7d022eec3f242b3b44cebd7cf00f90a5 Mon Sep 17 00:00:00 2001 From: Andrew Ayer Date: Mon, 7 Jul 2014 22:52:12 -0700 Subject: [PATCH] Simplify CTR code --- crypto.cpp | 27 ++++++++++++++------------- crypto.hpp | 7 ++++--- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/crypto.cpp b/crypto.cpp index db081ae..f2d9d28 100644 --- a/crypto.cpp +++ b/crypto.cpp @@ -32,32 +32,33 @@ #include "util.hpp" #include -Aes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* arg_nonce) +Aes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* nonce) : ecb(raw_key) { - std::memcpy(nonce, arg_nonce, NONCE_LEN); + // Set first 12 bytes of the CTR value to the nonce. + // This stays the same for the entirety of this object's lifetime. + std::memcpy(ctr_value, nonce, NONCE_LEN); byte_counter = 0; - std::memset(otp, '\0', sizeof(otp)); +} + +Aes_ctr_encryptor::~Aes_ctr_encryptor () +{ + std::memset(pad, '\0', BLOCK_LEN); } void Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, size_t len) { for (size_t i = 0; i < len; ++i) { if (byte_counter % BLOCK_LEN == 0) { - unsigned char ctr[BLOCK_LEN]; + // Set last 4 bytes of CTR to the (big-endian) block number (sequentially increasing with each block) + store_be32(ctr_value + NONCE_LEN, byte_counter / BLOCK_LEN); - // First 12 bytes of CTR: nonce - std::memcpy(ctr, nonce, NONCE_LEN); - - // Last 4 bytes of CTR: block number (sequentially increasing with each block) (big endian) - store_be32(ctr + NONCE_LEN, byte_counter / BLOCK_LEN); - - // Generate a new OTP - ecb.encrypt(ctr, otp); + // Generate a new pad + ecb.encrypt(ctr_value, pad); } // encrypt one byte - out[i] = in[i] ^ otp[byte_counter++ % BLOCK_LEN]; + out[i] = in[i] ^ pad[byte_counter++ % BLOCK_LEN]; if (byte_counter == 0) { throw Crypto_error("Aes_ctr_encryptor::process", "Too much data to encrypt securely"); diff --git a/crypto.hpp b/crypto.hpp index adc9643..db03241 100644 --- a/crypto.hpp +++ b/crypto.hpp @@ -76,12 +76,13 @@ public: private: Aes_ecb_encryptor ecb; - char nonce[NONCE_LEN];// First 96 bits of counter - uint32_t byte_counter; // How many bytes processed so far? - unsigned char otp[BLOCK_LEN]; // The current OTP that's in use + unsigned char ctr_value[BLOCK_LEN]; // Current CTR value (used as input to AES to derive pad) + unsigned char pad[BLOCK_LEN]; // Current encryption pad (output of AES) + uint32_t byte_counter; // How many bytes processed so far? public: Aes_ctr_encryptor (const unsigned char* key, const unsigned char* nonce); + ~Aes_ctr_encryptor (); void process (const unsigned char* in, unsigned char* out, size_t len);