Updated through tag hostap_2_5 from git://w1.fi/hostap.git
[mech_eap.git] / libeap / src / crypto / aes-unwrap.c
index f233ffa..ec793d9 100644 (file)
@@ -1,16 +1,10 @@
 /*
- * AES key unwrap (128-bit KEK, RFC3394)
+ * AES key unwrap (RFC3394)
  *
  * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
  *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as
- * published by the Free Software Foundation.
- *
- * Alternatively, this software may be distributed under the terms of BSD
- * license.
- *
- * See README and COPYING for more details.
+ * This software may be distributed under the terms of the BSD license.
+ * See README for more details.
  */
 
 #include "includes.h"
 #include "aes_wrap.h"
 
 /**
- * aes_unwrap - Unwrap key with AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
+ * aes_unwrap - Unwrap key with AES Key Wrap Algorithm (RFC3394)
  * @kek: Key encryption key (KEK)
+ * @kek_len: Length of KEK in octets
  * @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
  * bytes
  * @cipher: Wrapped key to be unwrapped, (n + 1) * 64 bits
  * @plain: Plaintext key, n * 64 bits
  * Returns: 0 on success, -1 on failure (e.g., integrity verification failed)
  */
-int aes_unwrap(const u8 *kek, int n, const u8 *cipher, u8 *plain)
+int aes_unwrap(const u8 *kek, size_t kek_len, int n, const u8 *cipher,
+              u8 *plain)
 {
-       u8 a[8], *r, b[16];
+       u8 a[8], *r, b[AES_BLOCK_SIZE];
        int i, j;
        void *ctx;
+       unsigned int t;
 
        /* 1) Initialize variables. */
        os_memcpy(a, cipher, 8);
        r = plain;
        os_memcpy(r, cipher + 8, 8 * n);
 
-       ctx = aes_decrypt_init(kek, 16);
+       ctx = aes_decrypt_init(kek, kek_len);
        if (ctx == NULL)
                return -1;
 
@@ -54,7 +51,11 @@ int aes_unwrap(const u8 *kek, int n, const u8 *cipher, u8 *plain)
                r = plain + (n - 1) * 8;
                for (i = n; i >= 1; i--) {
                        os_memcpy(b, a, 8);
-                       b[7] ^= n * j + i;
+                       t = n * j + i;
+                       b[7] ^= t;
+                       b[6] ^= t >> 8;
+                       b[5] ^= t >> 16;
+                       b[4] ^= t >> 24;
 
                        os_memcpy(b + 8, r, 8);
                        aes_decrypt(ctx, b, b);