1 /* $OpenBSD: cipher-aesctr.c,v 1.2 2015/01/14 10:24:42 markus Exp $ */
2 /*
3 * Copyright (c) 2003 Markus Friedl. All rights reserved.
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #include "includes.h"
19
20 #include <sys/types.h>
21 #include <string.h>
22
23 #ifndef WITH_OPENSSL
24
25 #include "cipher-aesctr.h"
26
27 /*
28 * increment counter 'ctr',
29 * the counter is of size 'len' bytes and stored in network-byte-order.
30 * (LSB at ctr[len-1], MSB at ctr[0])
31 */
32 static inline void
aesctr_inc(u8 * ctr,u32 len)33 aesctr_inc(u8 *ctr, u32 len)
34 {
35 ssize_t i;
36
37 #ifndef CONSTANT_TIME_INCREMENT
38 for (i = len - 1; i >= 0; i--)
39 if (++ctr[i]) /* continue on overflow */
40 return;
41 #else
42 u8 x, add = 1;
43
44 for (i = len - 1; i >= 0; i--) {
45 ctr[i] += add;
46 /* constant time for: x = ctr[i] ? 1 : 0 */
47 x = ctr[i];
48 x = (x | (x >> 4)) & 0xf;
49 x = (x | (x >> 2)) & 0x3;
50 x = (x | (x >> 1)) & 0x1;
51 add *= (x^1);
52 }
53 #endif
54 }
55
56 void
aesctr_keysetup(aesctr_ctx * x,const u8 * k,u32 kbits,u32 ivbits)57 aesctr_keysetup(aesctr_ctx *x,const u8 *k,u32 kbits,u32 ivbits)
58 {
59 x->rounds = rijndaelKeySetupEnc(x->ek, k, kbits);
60 }
61
62 void
aesctr_ivsetup(aesctr_ctx * x,const u8 * iv)63 aesctr_ivsetup(aesctr_ctx *x,const u8 *iv)
64 {
65 memcpy(x->ctr, iv, AES_BLOCK_SIZE);
66 }
67
68 void
aesctr_encrypt_bytes(aesctr_ctx * x,const u8 * m,u8 * c,u32 bytes)69 aesctr_encrypt_bytes(aesctr_ctx *x,const u8 *m,u8 *c,u32 bytes)
70 {
71 u32 n = 0;
72 u8 buf[AES_BLOCK_SIZE];
73
74 while ((bytes--) > 0) {
75 if (n == 0) {
76 rijndaelEncrypt(x->ek, x->rounds, x->ctr, buf);
77 aesctr_inc(x->ctr, AES_BLOCK_SIZE);
78 }
79 *(c++) = *(m++) ^ buf[n];
80 n = (n + 1) % AES_BLOCK_SIZE;
81 }
82 }
83 #endif /* !WITH_OPENSSL */
84