aes-unwrap.c revision 225736
198937Sdes/*
298937Sdes * AES key unwrap (128-bit KEK, RFC3394)
398937Sdes *
498937Sdes * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
598937Sdes *
698937Sdes * This program is free software; you can redistribute it and/or modify
798937Sdes * it under the terms of the GNU General Public License version 2 as
898937Sdes * published by the Free Software Foundation.
998937Sdes *
1098937Sdes * Alternatively, this software may be distributed under the terms of BSD
1198937Sdes * license.
1298937Sdes *
1398937Sdes * See README and COPYING for more details.
1498937Sdes */
1598937Sdes
1698937Sdes#include "includes.h"
1798937Sdes
1898937Sdes#include "common.h"
1998937Sdes#include "aes.h"
2098937Sdes#include "aes_wrap.h"
2198937Sdes
2298937Sdes/**
2398937Sdes * aes_unwrap - Unwrap key with AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
2498937Sdes * @kek: Key encryption key (KEK)
2598937Sdes * @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
2698937Sdes * bytes
2798937Sdes * @cipher: Wrapped key to be unwrapped, (n + 1) * 64 bits
2898937Sdes * @plain: Plaintext key, n * 64 bits
2998937Sdes * Returns: 0 on success, -1 on failure (e.g., integrity verification failed)
3098937Sdes */
3198937Sdesint aes_unwrap(const u8 *kek, int n, const u8 *cipher, u8 *plain)
3298937Sdes{
3398937Sdes	u8 a[8], *r, b[16];
3498937Sdes	int i, j;
3598937Sdes	void *ctx;
3698937Sdes
3798937Sdes	/* 1) Initialize variables. */
3898937Sdes	os_memcpy(a, cipher, 8);
3998937Sdes	r = plain;
4098937Sdes	os_memcpy(r, cipher + 8, 8 * n);
4198937Sdes
4298937Sdes	ctx = aes_decrypt_init(kek, 16);
4398937Sdes	if (ctx == NULL)
4498937Sdes		return -1;
4598937Sdes
4698937Sdes	/* 2) Compute intermediate values.
4798937Sdes	 * For j = 5 to 0
4898937Sdes	 *     For i = n to 1
4998937Sdes	 *         B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i
5098937Sdes	 *         A = MSB(64, B)
5198937Sdes	 *         R[i] = LSB(64, B)
5298937Sdes	 */
5398937Sdes	for (j = 5; j >= 0; j--) {
5498937Sdes		r = plain + (n - 1) * 8;
5598937Sdes		for (i = n; i >= 1; i--) {
5698937Sdes			os_memcpy(b, a, 8);
5798937Sdes			b[7] ^= n * j + i;
5898937Sdes
5998937Sdes			os_memcpy(b + 8, r, 8);
6098937Sdes			aes_decrypt(ctx, b, b);
6198937Sdes			os_memcpy(a, b, 8);
6298937Sdes			os_memcpy(r, b + 8, 8);
6398937Sdes			r -= 8;
6498937Sdes		}
6598937Sdes	}
6698937Sdes	aes_decrypt_deinit(ctx);
6798937Sdes
6898937Sdes	/* 3) Output results.
6998937Sdes	 *
7098937Sdes	 * These are already in @plain due to the location of temporary
7198937Sdes	 * variables. Just verify that the IV matches with the expected value.
7298937Sdes	 */
7398937Sdes	for (i = 0; i < 8; i++) {
7498937Sdes		if (a[i] != 0xa6)
7598937Sdes			return -1;
7698937Sdes	}
7798937Sdes
7898937Sdes	return 0;
7998937Sdes}
8098937Sdes