1214501Srpaulo/* 2214501Srpaulo * AES Key Wrap Algorithm (128-bit KEK) (RFC3394) 3214501Srpaulo * 4214501Srpaulo * Copyright (c) 2003-2007, Jouni Malinen <j@w1.fi> 5214501Srpaulo * 6214501Srpaulo * This program is free software; you can redistribute it and/or modify 7214501Srpaulo * it under the terms of the GNU General Public License version 2 as 8214501Srpaulo * published by the Free Software Foundation. 9214501Srpaulo * 10214501Srpaulo * Alternatively, this software may be distributed under the terms of BSD 11214501Srpaulo * license. 12214501Srpaulo * 13214501Srpaulo * See README and COPYING for more details. 14214501Srpaulo */ 15214501Srpaulo 16214501Srpaulo#include "includes.h" 17214501Srpaulo 18214501Srpaulo#include "common.h" 19214501Srpaulo#include "aes.h" 20214501Srpaulo#include "aes_wrap.h" 21214501Srpaulo 22214501Srpaulo/** 23214501Srpaulo * aes_wrap - Wrap keys with AES Key Wrap Algorithm (128-bit KEK) (RFC3394) 24214501Srpaulo * @kek: 16-octet Key encryption key (KEK) 25214501Srpaulo * @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16 26214501Srpaulo * bytes 27214501Srpaulo * @plain: Plaintext key to be wrapped, n * 64 bits 28214501Srpaulo * @cipher: Wrapped key, (n + 1) * 64 bits 29214501Srpaulo * Returns: 0 on success, -1 on failure 30214501Srpaulo */ 31214501Srpauloint aes_wrap(const u8 *kek, int n, const u8 *plain, u8 *cipher) 32214501Srpaulo{ 33214501Srpaulo u8 *a, *r, b[16]; 34214501Srpaulo int i, j; 35214501Srpaulo void *ctx; 36214501Srpaulo 37214501Srpaulo a = cipher; 38214501Srpaulo r = cipher + 8; 39214501Srpaulo 40214501Srpaulo /* 1) Initialize variables. */ 41214501Srpaulo os_memset(a, 0xa6, 8); 42214501Srpaulo os_memcpy(r, plain, 8 * n); 43214501Srpaulo 44214501Srpaulo ctx = aes_encrypt_init(kek, 16); 45214501Srpaulo if (ctx == NULL) 46214501Srpaulo return -1; 47214501Srpaulo 48214501Srpaulo /* 2) Calculate intermediate values. 49214501Srpaulo * For j = 0 to 5 50214501Srpaulo * For i=1 to n 51214501Srpaulo * B = AES(K, A | R[i]) 52214501Srpaulo * A = MSB(64, B) ^ t where t = (n*j)+i 53214501Srpaulo * R[i] = LSB(64, B) 54214501Srpaulo */ 55214501Srpaulo for (j = 0; j <= 5; j++) { 56214501Srpaulo r = cipher + 8; 57214501Srpaulo for (i = 1; i <= n; i++) { 58214501Srpaulo os_memcpy(b, a, 8); 59214501Srpaulo os_memcpy(b + 8, r, 8); 60214501Srpaulo aes_encrypt(ctx, b, b); 61214501Srpaulo os_memcpy(a, b, 8); 62214501Srpaulo a[7] ^= n * j + i; 63214501Srpaulo os_memcpy(r, b + 8, 8); 64214501Srpaulo r += 8; 65214501Srpaulo } 66214501Srpaulo } 67214501Srpaulo aes_encrypt_deinit(ctx); 68214501Srpaulo 69214501Srpaulo /* 3) Output the results. 70214501Srpaulo * 71214501Srpaulo * These are already in @cipher due to the location of temporary 72214501Srpaulo * variables. 73214501Srpaulo */ 74214501Srpaulo 75214501Srpaulo return 0; 76214501Srpaulo} 77