2 * Copyright (c) 2009 Joshua Oreman <oremanj@rwcr.net>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 FILE_LICENCE ( GPL2_OR_LATER
);
24 #include <ipxe/crypto.h>
28 * Wrap a key or other data using AES Key Wrap (RFC 3394)
30 * @v kek Key Encryption Key, 16 bytes
31 * @v src Data to encrypt
32 * @v nblk Number of 8-byte blocks in @a data
33 * @ret dest Encrypted data (8 bytes longer than input)
35 * The algorithm is implemented such that @a src and @a dest may point
38 int aes_wrap ( const void *kek
, const void *src
, void *dest
, int nblk
)
44 void *aes_ctx
= malloc ( AES_CTX_SIZE
);
49 cipher_setkey ( &aes_algorithm
, aes_ctx
, kek
, 16 );
52 memset ( A
, 0xA6, 8 );
53 memmove ( dest
+ 8, src
, nblk
* 8 );
56 for ( j
= 0; j
< 6; j
++ ) {
58 for ( i
= 1; i
<= nblk
; i
++ ) {
60 memcpy ( B
+ 8, R
, 8 );
61 cipher_encrypt ( &aes_algorithm
, aes_ctx
, B
, B
, 16 );
63 A
[7] ^= ( nblk
* j
) + i
;
64 memcpy ( R
, B
+ 8, 8 );
74 * Unwrap a key or other data using AES Key Wrap (RFC 3394)
76 * @v kek Key Encryption Key, 16 bytes
77 * @v src Data to decrypt
78 * @v nblk Number of 8-byte blocks in @e plaintext key
79 * @ret dest Decrypted data (8 bytes shorter than input)
80 * @ret rc Zero on success, nonzero on IV mismatch
82 * The algorithm is implemented such that @a src and @a dest may point
85 int aes_unwrap ( const void *kek
, const void *src
, void *dest
, int nblk
)
90 void *aes_ctx
= malloc ( AES_CTX_SIZE
);
95 cipher_setkey ( &aes_algorithm
, aes_ctx
, kek
, 16 );
99 memmove ( dest
, src
+ 8, nblk
* 8 );
102 for ( j
= 5; j
>= 0; j
-- ) {
103 R
= dest
+ ( nblk
- 1 ) * 8;
104 for ( i
= nblk
; i
>= 1; i
-- ) {
106 memcpy ( B
+ 8, R
, 8 );
107 B
[7] ^= ( nblk
* j
) + i
;
108 cipher_decrypt ( &aes_algorithm
, aes_ctx
, B
, B
, 16 );
110 memcpy ( R
, B
+ 8, 8 );
118 for ( i
= 0; i
< 8; i
++ ) {