2 AES-CMAC-128 (rfc 4493)
3 Copyright (C) Stefan Metzmacher 2012
4 Copyright (C) Jeremy Allison 2012
5 Copyright (C) Michael Adam 2012
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "../lib/crypto/crypto.h"
24 static const uint8_t const_Zero
[] = {
25 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
26 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
29 static const uint8_t const_Rb
[] = {
30 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
31 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87
34 #define _MSB(x) (((x)[0] & 0x80)?1:0)
36 void aes_cmac_128_init(struct aes_cmac_128_context
*ctx
,
37 const uint8_t K
[AES_BLOCK_SIZE
])
41 AES_set_encrypt_key(K
, 128, &ctx
->aes_key
);
43 /* step 1 - generate subkeys k1 and k2 */
45 AES_encrypt(const_Zero
, ctx
->L
, &ctx
->aes_key
);
47 if (_MSB(ctx
->L
) == 0) {
48 aes_block_lshift(ctx
->L
, ctx
->K1
);
50 aes_block_lshift(ctx
->L
, ctx
->tmp
);
51 aes_block_xor(ctx
->tmp
, const_Rb
, ctx
->K1
);
54 if (_MSB(ctx
->K1
) == 0) {
55 aes_block_lshift(ctx
->K1
, ctx
->K2
);
57 aes_block_lshift(ctx
->K1
, ctx
->tmp
);
58 aes_block_xor(ctx
->tmp
, const_Rb
, ctx
->K2
);
62 void aes_cmac_128_update(struct aes_cmac_128_context
*ctx
,
63 const uint8_t *msg
, size_t msg_len
)
66 * check if we expand the block
68 if (ctx
->last_len
< AES_BLOCK_SIZE
) {
69 size_t len
= MIN(AES_BLOCK_SIZE
- ctx
->last_len
, msg_len
);
71 memcpy(&ctx
->last
[ctx
->last_len
], msg
, len
);
78 /* if it is still the last block, we are done */
83 * now checksum everything but the last block
85 aes_block_xor(ctx
->X
, ctx
->last
, ctx
->Y
);
86 AES_encrypt(ctx
->Y
, ctx
->X
, &ctx
->aes_key
);
88 while (msg_len
> AES_BLOCK_SIZE
) {
89 aes_block_xor(ctx
->X
, msg
, ctx
->Y
);
90 AES_encrypt(ctx
->Y
, ctx
->X
, &ctx
->aes_key
);
91 msg
+= AES_BLOCK_SIZE
;
92 msg_len
-= AES_BLOCK_SIZE
;
96 * copy the last block, it will be processed in
97 * aes_cmac_128_final().
99 ZERO_STRUCT(ctx
->last
);
100 memcpy(ctx
->last
, msg
, msg_len
);
101 ctx
->last_len
= msg_len
;
104 void aes_cmac_128_final(struct aes_cmac_128_context
*ctx
,
105 uint8_t T
[AES_BLOCK_SIZE
])
107 if (ctx
->last_len
< AES_BLOCK_SIZE
) {
108 ctx
->last
[ctx
->last_len
] = 0x80;
109 aes_block_xor(ctx
->last
, ctx
->K2
, ctx
->tmp
);
111 aes_block_xor(ctx
->last
, ctx
->K1
, ctx
->tmp
);
114 aes_block_xor(ctx
->tmp
, ctx
->X
, ctx
->Y
);
115 AES_encrypt(ctx
->Y
, T
, &ctx
->aes_key
);