huangcm
2025-07-01 676035278781360996553c427a12bf358249ebf7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
 * AES key unwrap (RFC3394)
 *
 * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi>
 *
 * This software may be distributed under the terms of the BSD license.
 * See README for more details.
 */
 
#include "includes.h"
 
#include "common.h"
#include "aes.h"
#include "aes_wrap.h"
 
/**
 * 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, size_t kek_len, int n, const u8 *cipher,
          u8 *plain)
{
   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, kek_len);
   if (ctx == NULL)
       return -1;
 
   /* 2) Compute intermediate values.
    * For j = 5 to 0
    *     For i = n to 1
    *         B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i
    *         A = MSB(64, B)
    *         R[i] = LSB(64, B)
    */
   for (j = 5; j >= 0; j--) {
       r = plain + (n - 1) * 8;
       for (i = n; i >= 1; i--) {
           os_memcpy(b, a, 8);
           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);
           os_memcpy(a, b, 8);
           os_memcpy(r, b + 8, 8);
           r -= 8;
       }
   }
   aes_decrypt_deinit(ctx);
 
   /* 3) Output results.
    *
    * These are already in @plain due to the location of temporary
    * variables. Just verify that the IV matches with the expected value.
    */
   for (i = 0; i < 8; i++) {
       if (a[i] != 0xa6)
           return -1;
   }
 
   return 0;
}