2 * Copyright (C) 2009 Michael Brown <mbrown@fensystems.co.uk>.
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>
29 * Cipher-block chaining
37 * @v dst Second input data and output data buffer
38 * @v len Length of data
40 static void cbc_xor ( const void *src, void *dst, size_t len ) {
41 const uint32_t *srcl = src;
45 /* Assume that block sizes will always be dword-aligned, for speed */
46 assert ( ( len % sizeof ( *srcl ) ) == 0 );
48 for ( i = 0 ; i < ( len / sizeof ( *srcl ) ) ; i++ )
56 * @v src Data to encrypt
57 * @v dst Buffer for encrypted data
58 * @v len Length of data
59 * @v raw_cipher Underlying cipher algorithm
60 * @v cbc_ctx CBC context
62 void cbc_encrypt ( void *ctx, const void *src, void *dst, size_t len,
63 struct cipher_algorithm *raw_cipher, void *cbc_ctx ) {
64 size_t blocksize = raw_cipher->blocksize;
66 assert ( ( len % blocksize ) == 0 );
69 cbc_xor ( src, cbc_ctx, blocksize );
70 cipher_encrypt ( raw_cipher, ctx, cbc_ctx, dst, blocksize );
71 memcpy ( cbc_ctx, dst, blocksize );
82 * @v src Data to decrypt
83 * @v dst Buffer for decrypted data
84 * @v len Length of data
85 * @v raw_cipher Underlying cipher algorithm
86 * @v cbc_ctx CBC context
88 void cbc_decrypt ( void *ctx, const void *src, void *dst, size_t len,
89 struct cipher_algorithm *raw_cipher, void *cbc_ctx ) {
90 size_t blocksize = raw_cipher->blocksize;
91 uint8_t next_cbc_ctx[blocksize];
93 assert ( ( len % blocksize ) == 0 );
96 memcpy ( next_cbc_ctx, src, blocksize );
97 cipher_decrypt ( raw_cipher, ctx, src, dst, blocksize );
98 cbc_xor ( cbc_ctx, dst, blocksize );
99 memcpy ( cbc_ctx, next_cbc_ctx, blocksize );