2009-08-13 04:40:28 -04:00
|
|
|
/*
|
2014-10-07 06:48:45 -04:00
|
|
|
* AES Key Wrap Algorithm (RFC3394)
|
2009-08-13 04:40:28 -04:00
|
|
|
*
|
|
|
|
* Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
|
|
|
|
*
|
2012-02-11 09:46:35 -05:00
|
|
|
* This software may be distributed under the terms of the BSD license.
|
|
|
|
* See README for more details.
|
2009-08-13 04:40:28 -04:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include "includes.h"
|
|
|
|
|
|
|
|
#include "common.h"
|
2009-08-17 13:27:25 -04:00
|
|
|
#include "aes.h"
|
2009-12-28 09:01:21 -05:00
|
|
|
#include "aes_wrap.h"
|
2009-08-13 04:40:28 -04:00
|
|
|
|
|
|
|
/**
|
2014-10-07 06:48:45 -04:00
|
|
|
* aes_wrap - Wrap keys with AES Key Wrap Algorithm (RFC3394)
|
|
|
|
* @kek: Key encryption key (KEK)
|
|
|
|
* @kek_len: Length of KEK in octets
|
2009-08-13 04:40:28 -04:00
|
|
|
* @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
|
|
|
|
* bytes
|
|
|
|
* @plain: Plaintext key to be wrapped, n * 64 bits
|
|
|
|
* @cipher: Wrapped key, (n + 1) * 64 bits
|
|
|
|
* Returns: 0 on success, -1 on failure
|
|
|
|
*/
|
2014-10-07 06:48:45 -04:00
|
|
|
int aes_wrap(const u8 *kek, size_t kek_len, int n, const u8 *plain, u8 *cipher)
|
2009-08-13 04:40:28 -04:00
|
|
|
{
|
2014-10-07 06:48:45 -04:00
|
|
|
u8 *a, *r, b[AES_BLOCK_SIZE];
|
2009-08-13 04:40:28 -04:00
|
|
|
int i, j;
|
|
|
|
void *ctx;
|
2014-10-07 07:45:22 -04:00
|
|
|
unsigned int t;
|
2009-08-13 04:40:28 -04:00
|
|
|
|
|
|
|
a = cipher;
|
|
|
|
r = cipher + 8;
|
|
|
|
|
|
|
|
/* 1) Initialize variables. */
|
|
|
|
os_memset(a, 0xa6, 8);
|
|
|
|
os_memcpy(r, plain, 8 * n);
|
|
|
|
|
2014-10-07 06:48:45 -04:00
|
|
|
ctx = aes_encrypt_init(kek, kek_len);
|
2009-08-13 04:40:28 -04:00
|
|
|
if (ctx == NULL)
|
|
|
|
return -1;
|
|
|
|
|
|
|
|
/* 2) Calculate intermediate values.
|
|
|
|
* For j = 0 to 5
|
|
|
|
* For i=1 to n
|
|
|
|
* B = AES(K, A | R[i])
|
|
|
|
* A = MSB(64, B) ^ t where t = (n*j)+i
|
|
|
|
* R[i] = LSB(64, B)
|
|
|
|
*/
|
|
|
|
for (j = 0; j <= 5; j++) {
|
|
|
|
r = cipher + 8;
|
|
|
|
for (i = 1; i <= n; i++) {
|
|
|
|
os_memcpy(b, a, 8);
|
|
|
|
os_memcpy(b + 8, r, 8);
|
|
|
|
aes_encrypt(ctx, b, b);
|
|
|
|
os_memcpy(a, b, 8);
|
2014-10-07 07:45:22 -04:00
|
|
|
t = n * j + i;
|
|
|
|
a[7] ^= t;
|
|
|
|
a[6] ^= t >> 8;
|
|
|
|
a[5] ^= t >> 16;
|
|
|
|
a[4] ^= t >> 24;
|
2009-08-13 04:40:28 -04:00
|
|
|
os_memcpy(r, b + 8, 8);
|
|
|
|
r += 8;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
aes_encrypt_deinit(ctx);
|
|
|
|
|
|
|
|
/* 3) Output the results.
|
|
|
|
*
|
|
|
|
* These are already in @cipher due to the location of temporary
|
|
|
|
* variables.
|
|
|
|
*/
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|