blob: 7ed34e803e4e53383793d3f4278b033636090f6d [file] [log] [blame]
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001/*
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -07002 * AES Key Wrap Algorithm (RFC3394)
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07003 *
4 * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
5 *
Dmitry Shmidtc5ec7f52012-03-06 16:33:24 -08006 * This software may be distributed under the terms of the BSD license.
7 * See README for more details.
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07008 */
9
10#include "includes.h"
11
12#include "common.h"
13#include "aes.h"
14#include "aes_wrap.h"
15
16/**
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -070017 * aes_wrap - Wrap keys with AES Key Wrap Algorithm (RFC3394)
18 * @kek: Key encryption key (KEK)
19 * @kek_len: Length of KEK in octets
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070020 * @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 */
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -070026int aes_wrap(const u8 *kek, size_t kek_len, int n, const u8 *plain, u8 *cipher)
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070027{
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -070028 u8 *a, *r, b[AES_BLOCK_SIZE];
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070029 int i, j;
30 void *ctx;
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -070031 unsigned int t;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070032
33 a = cipher;
34 r = cipher + 8;
35
36 /* 1) Initialize variables. */
37 os_memset(a, 0xa6, 8);
38 os_memcpy(r, plain, 8 * n);
39
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -070040 ctx = aes_encrypt_init(kek, kek_len);
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070041 if (ctx == NULL)
42 return -1;
43
44 /* 2) Calculate intermediate values.
45 * For j = 0 to 5
46 * For i=1 to n
47 * B = AES(K, A | R[i])
48 * A = MSB(64, B) ^ t where t = (n*j)+i
49 * R[i] = LSB(64, B)
50 */
51 for (j = 0; j <= 5; j++) {
52 r = cipher + 8;
53 for (i = 1; i <= n; i++) {
54 os_memcpy(b, a, 8);
55 os_memcpy(b + 8, r, 8);
56 aes_encrypt(ctx, b, b);
57 os_memcpy(a, b, 8);
Dmitry Shmidt9ead16e2014-10-07 13:15:23 -070058 t = n * j + i;
59 a[7] ^= t;
60 a[6] ^= t >> 8;
61 a[5] ^= t >> 16;
62 a[4] ^= t >> 24;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070063 os_memcpy(r, b + 8, 8);
64 r += 8;
65 }
66 }
67 aes_encrypt_deinit(ctx);
68
69 /* 3) Output the results.
70 *
71 * These are already in @cipher due to the location of temporary
72 * variables.
73 */
74
75 return 0;
76}