1/* 2 * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. 3 * 4 * Licensed under the OpenSSL license (the "License"). You may not use 5 * this file except in compliance with the License. You can obtain a copy 6 * in the file LICENSE in the source distribution or at 7 * https://www.openssl.org/source/license.html 8 */ 9 10#include <assert.h> 11#include <string.h> 12 13#include "internal.h" 14#include "../../internal.h" 15 16 17static_assert(16 % sizeof(crypto_word_t) == 0, 18 "block cannot be divided into crypto_word_t"); 19 20// increment upper 96 bits of 128-bit counter by 1 21static void ctr96_inc(uint8_t *counter) { 22 uint32_t n = 12, c = 1; 23 24 do { 25 --n; 26 c += counter[n]; 27 counter[n] = (uint8_t) c; 28 c >>= 8; 29 } while (n); 30} 31 32void CRYPTO_ctr128_encrypt_ctr32(const uint8_t *in, uint8_t *out, size_t len, 33 const AES_KEY *key, uint8_t ivec[16], 34 uint8_t ecount_buf[16], unsigned int *num, 35 ctr128_f func) { 36 unsigned int n, ctr32; 37 38 assert(key && ecount_buf && num); 39 assert(len == 0 || (in && out)); 40 assert(*num < 16); 41 42 n = *num; 43 44 while (n && len) { 45 *(out++) = *(in++) ^ ecount_buf[n]; 46 --len; 47 n = (n + 1) % 16; 48 } 49 50 ctr32 = CRYPTO_load_u32_be(ivec + 12); 51 while (len >= 16) { 52 size_t blocks = len / 16; 53 // 1<<28 is just a not-so-small yet not-so-large number... 54 // Below condition is practically never met, but it has to 55 // be checked for code correctness. 56 if (sizeof(size_t) > sizeof(unsigned int) && blocks > (1U << 28)) { 57 blocks = (1U << 28); 58 } 59 // As (*func) operates on 32-bit counter, caller 60 // has to handle overflow. 'if' below detects the 61 // overflow, which is then handled by limiting the 62 // amount of blocks to the exact overflow point... 63 ctr32 += (uint32_t)blocks; 64 if (ctr32 < blocks) { 65 blocks -= ctr32; 66 ctr32 = 0; 67 } 68 (*func)(in, out, blocks, key, ivec); 69 // (*func) does not update ivec, caller does: 70 CRYPTO_store_u32_be(ivec + 12, ctr32); 71 // ... overflow was detected, propogate carry. 72 if (ctr32 == 0) { 73 ctr96_inc(ivec); 74 } 75 blocks *= 16; 76 len -= blocks; 77 out += blocks; 78 in += blocks; 79 } 80 if (len) { 81 OPENSSL_memset(ecount_buf, 0, 16); 82 (*func)(ecount_buf, ecount_buf, 1, key, ivec); 83 ++ctr32; 84 CRYPTO_store_u32_be(ivec + 12, ctr32); 85 if (ctr32 == 0) { 86 ctr96_inc(ivec); 87 } 88 while (len--) { 89 out[n] = in[n] ^ ecount_buf[n]; 90 ++n; 91 } 92 } 93 94 *num = n; 95} 96