]> git.ipfire.org Git - thirdparty/hostap.git/blob - src/crypto/aes-wrap.c
AES: Extend key wrap design to support longer AES keys
[thirdparty/hostap.git] / src / crypto / aes-wrap.c
1 /*
2 * AES Key Wrap Algorithm (RFC3394)
3 *
4 * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
5 *
6 * This software may be distributed under the terms of the BSD license.
7 * See README for more details.
8 */
9
10 #include "includes.h"
11
12 #include "common.h"
13 #include "aes.h"
14 #include "aes_wrap.h"
15
16 /**
17 * aes_wrap - Wrap keys with AES Key Wrap Algorithm (RFC3394)
18 * @kek: Key encryption key (KEK)
19 * @kek_len: Length of KEK in octets
20 * @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
21 * bytes
22 * @plain: Plaintext key to be wrapped, n * 64 bits
23 * @cipher: Wrapped key, (n + 1) * 64 bits
24 * Returns: 0 on success, -1 on failure
25 */
26 int aes_wrap(const u8 *kek, size_t kek_len, int n, const u8 *plain, u8 *cipher)
27 {
28 u8 *a, *r, b[AES_BLOCK_SIZE];
29 int i, j;
30 void *ctx;
31
32 a = cipher;
33 r = cipher + 8;
34
35 /* 1) Initialize variables. */
36 os_memset(a, 0xa6, 8);
37 os_memcpy(r, plain, 8 * n);
38
39 ctx = aes_encrypt_init(kek, kek_len);
40 if (ctx == NULL)
41 return -1;
42
43 /* 2) Calculate intermediate values.
44 * For j = 0 to 5
45 * For i=1 to n
46 * B = AES(K, A | R[i])
47 * A = MSB(64, B) ^ t where t = (n*j)+i
48 * R[i] = LSB(64, B)
49 */
50 for (j = 0; j <= 5; j++) {
51 r = cipher + 8;
52 for (i = 1; i <= n; i++) {
53 os_memcpy(b, a, 8);
54 os_memcpy(b + 8, r, 8);
55 aes_encrypt(ctx, b, b);
56 os_memcpy(a, b, 8);
57 a[7] ^= n * j + i;
58 os_memcpy(r, b + 8, 8);
59 r += 8;
60 }
61 }
62 aes_encrypt_deinit(ctx);
63
64 /* 3) Output the results.
65 *
66 * These are already in @cipher due to the location of temporary
67 * variables.
68 */
69
70 return 0;
71 }