From c68481052a88ab1749aed9c4f6a801936d04a276 Mon Sep 17 00:00:00 2001 From: levlam Date: Sat, 13 Jun 2020 04:45:40 +0300 Subject: [PATCH] AES CTR improvements. GitOrigin-RevId: c4ed8fdc883fdf7cc2ed10334d3bb9487d590d41 --- benchmark/bench_crypto.cpp | 2 +- tdutils/td/utils/crypto.cpp | 18 ++++++++++-------- tdutils/td/utils/crypto.h | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/benchmark/bench_crypto.cpp b/benchmark/bench_crypto.cpp index 0b313b43a..e861914c5 100644 --- a/benchmark/bench_crypto.cpp +++ b/benchmark/bench_crypto.cpp @@ -73,7 +73,7 @@ class AesEcbBench : public td::Benchmark { for (int i = 0; i <= n; i++) { size_t step = 16; for (size_t offset = 0; offset + step <= data_slice.size(); offset += step) { - state.encrypt(data_slice.ubegin() + offset, data_slice.ubegin() + offset, (int)step); + state.encrypt(data_slice.ubegin() + offset, data_slice.ubegin() + offset, static_cast(step)); } } } diff --git a/tdutils/td/utils/crypto.cpp b/tdutils/td/utils/crypto.cpp index 175bb79f6..4908eecda 100644 --- a/tdutils/td/utils/crypto.cpp +++ b/tdutils/td/utils/crypto.cpp @@ -382,8 +382,8 @@ class AesCtrState::Impl { auto n = from.size(); while (n != 0) { if (current.empty()) { - if (N != 1) { - counter.as_mutable_slice().copy_from(counter.as_slice().substr((N - 1) * AES_BLOCK_SIZE)); + if (BLOCK_COUNT != 1) { + counter.as_mutable_slice().copy_from(counter.as_slice().substr((BLOCK_COUNT - 1) * AES_BLOCK_SIZE)); } inc(counter.as_mutable_slice().ubegin()); fill(); @@ -403,9 +403,9 @@ class AesCtrState::Impl { private: AesState aes_state; - static constexpr size_t N = 32; - SecureString counter{AES_BLOCK_SIZE * N}; - SecureString encrypted_counter{AES_BLOCK_SIZE * N}; + static constexpr size_t BLOCK_COUNT = 32; + SecureString counter{AES_BLOCK_SIZE * BLOCK_COUNT}; + SecureString encrypted_counter{AES_BLOCK_SIZE * BLOCK_COUNT}; Slice current; void inc(uint8 *ptr) { @@ -415,17 +415,19 @@ class AesCtrState::Impl { } } } + void fill() { auto *src = counter.as_slice().ubegin(); auto *dst = counter.as_mutable_slice().ubegin() + AES_BLOCK_SIZE; - for (size_t i = 0; i + 1 < N; i++) { - memcpy(dst, src, AES_BLOCK_SIZE); + for (size_t i = 0; i + 1 < BLOCK_COUNT; i++) { + std::memcpy(dst, src, AES_BLOCK_SIZE); inc(dst); src += AES_BLOCK_SIZE; dst += AES_BLOCK_SIZE; } - aes_state.encrypt(counter.as_slice().ubegin(), encrypted_counter.as_mutable_slice().ubegin(), (int)counter.size()); + aes_state.encrypt(counter.as_slice().ubegin(), encrypted_counter.as_mutable_slice().ubegin(), + static_cast(counter.size())); current = encrypted_counter.as_slice(); } }; diff --git a/tdutils/td/utils/crypto.h b/tdutils/td/utils/crypto.h index 2996e72d2..c97ad4c22 100644 --- a/tdutils/td/utils/crypto.h +++ b/tdutils/td/utils/crypto.h @@ -19,7 +19,7 @@ uint64 pq_factorize(uint64 pq); #if TD_HAVE_OPENSSL void init_crypto(); -struct AesState { +class AesState { public: AesState(); AesState(const AesState &from) = delete;