00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 FILE_LICENCE ( GPL2_OR_LATER );
00020
00021 #include <stdlib.h>
00022 #include <string.h>
00023 #include <gpxe/crypto.h>
00024 #include <gpxe/aes.h>
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037 int aes_wrap ( const void *kek, const void *src, void *dest, int nblk )
00038 {
00039 u8 *A = dest;
00040 u8 B[16];
00041 u8 *R;
00042 int i, j;
00043 void *aes_ctx = malloc ( AES_CTX_SIZE );
00044
00045 if ( ! aes_ctx )
00046 return -1;
00047
00048 cipher_setkey ( &aes_algorithm, aes_ctx, kek, 16 );
00049
00050
00051 memset ( A, 0xA6, sizeof ( A ) );
00052 memmove ( dest + 8, src, nblk * 8 );
00053
00054
00055 for ( j = 0; j < 6; j++ ) {
00056 R = dest + 8;
00057 for ( i = 1; i <= nblk; i++ ) {
00058 memcpy ( B, A, 8 );
00059 memcpy ( B + 8, R, 8 );
00060 cipher_encrypt ( &aes_algorithm, aes_ctx, B, B, 16 );
00061 memcpy ( A, B, 8 );
00062 A[7] ^= ( nblk * j ) + i;
00063 memcpy ( R, B + 8, 8 );
00064 R += 8;
00065 }
00066 }
00067
00068 free ( aes_ctx );
00069 return 0;
00070 }
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084 int aes_unwrap ( const void *kek, const void *src, void *dest, int nblk )
00085 {
00086 u8 A[8], B[16];
00087 u8 *R;
00088 int i, j;
00089 void *aes_ctx = malloc ( AES_CTX_SIZE );
00090
00091 if ( ! aes_ctx )
00092 return -1;
00093
00094 cipher_setkey ( &aes_algorithm, aes_ctx, kek, 16 );
00095
00096
00097 memcpy ( A, src, 8 );
00098 memmove ( dest, src + 8, nblk * 8 );
00099
00100
00101 for ( j = 5; j >= 0; j-- ) {
00102 R = dest + ( nblk - 1 ) * 8;
00103 for ( i = nblk; i >= 1; i-- ) {
00104 memcpy ( B, A, 8 );
00105 memcpy ( B + 8, R, 8 );
00106 B[7] ^= ( nblk * j ) + i;
00107 cipher_decrypt ( &aes_algorithm, aes_ctx, B, B, 16 );
00108 memcpy ( A, B, 8 );
00109 memcpy ( R, B + 8, 8 );
00110 R -= 8;
00111 }
00112 }
00113
00114 free ( aes_ctx );
00115
00116
00117 for ( i = 0; i < 8; i++ ) {
00118 if ( A[i] != 0xA6 )
00119 return -1;
00120 }
00121
00122 return 0;
00123 }