1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2013 Free Software Foundation, Inc.
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <string.h>
20
21 #include "libpspp/cmac-aes256.h"
22 #include "libpspp/cast.h"
23
24 #include "gl/rijndael-alg-fst.h"
25
26 static void
gen_subkey(const uint8_t in[16],uint8_t out[16])27 gen_subkey (const uint8_t in[16], uint8_t out[16])
28 {
29 size_t i;
30
31 for (i = 0; i < 15; i++)
32 out[i] = (in[i] << 1) | (in[i + 1] >> 7);
33 out[15] = in[15] << 1;
34
35 if (in[0] & 0x80)
36 out[15] ^= 0x87;
37 }
38
39 /* Computes CMAC-AES-256 of the SIZE bytes in DATA, using the 256-bit AES key
40 KEY. Stores the result in the 128-bit CMAC. */
41 void
cmac_aes256(const uint8_t key[32],const void * data_,size_t size,uint8_t cmac[16])42 cmac_aes256(const uint8_t key[32],
43 const void *data_, size_t size,
44 uint8_t cmac[16])
45 {
46 const char zeros[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
47 uint32_t rk[4 * (RIJNDAEL_MAXNR + 1)];
48 uint8_t k1[16], k2[16], L[16];
49 const uint8_t *data = data_;
50 uint8_t c[16], tmp[16];
51 int Nr;
52 int i;
53
54 Nr = rijndaelKeySetupEnc (rk, CHAR_CAST (const char *, key), 256);
55
56 rijndaelEncrypt (rk, Nr, zeros, CHAR_CAST (char *, L));
57 gen_subkey (L, k1);
58 gen_subkey (k1, k2);
59
60 memset (c, 0, 16);
61 while (size > 16)
62 {
63 for (i = 0; i < 16; i++)
64 tmp[i] = c[i] ^ data[i];
65 rijndaelEncrypt (rk, Nr, CHAR_CAST (const char *, tmp),
66 CHAR_CAST (char *, c));
67
68 size -= 16;
69 data += 16;
70 }
71
72 if (size == 16)
73 {
74 for (i = 0; i < 16; i++)
75 tmp[i] = c[i] ^ data[i] ^ k1[i];
76 }
77 else
78 {
79 for (i = 0; i < 16; i++)
80 tmp[i] = c[i] ^ k2[i];
81 for (i = 0; i < size; i++)
82 tmp[i] ^= data[i];
83 tmp[size] ^= 0x80;
84 }
85 rijndaelEncrypt (rk, Nr, CHAR_CAST (const char *, tmp),
86 CHAR_CAST (char *, cmac));
87 }
88