Cryptography Reference
In-Depth Information
bytes. Because you're working with byte arrays that must end on an 8-bit (one-
byte) boundary, this means that, if the input block is less than eight bytes, you
add the byte 0x80 (128), followed by zero bytes to pad. The decryption routine
just starts at the end of the decrypted output, removing zero bytes until 0x80 is
encountered, removes that, and returns the result to the caller.
Under this padding scheme, an input of, for example, “abcdef” (six characters)
needs to have two bytes added to it. Therefore, “abcdef” would become
61 62 63 64 65 66 80 00
a b c d e f
This would be encrypted under DES (using, say, a key of the ASCII string
password ) to the hex string: 25 ac 8f c5 c4 2f 89 5d. The decryption routine would
then decrypt it to a, b, c, d, e, f, 0x80, 0x00, search backward from the end for
the fi rst occurrence of 0x80, and remove everything after it. If the input string
happened to actually end with hex byte 0x80, the decryptor would see 0x80
0x80 0x0 ... and still correctly remove only the padding.
There's one wrinkle here; if the input did end on an eight-byte boundary that
happened to contain 0 bytes following a 0x80, the decryption routine would
remove legitimate input. Therefore, if the input ends on an eight-byte boundary,
you have to add a whole block of padding (0x80 0x0 0x0 0x0 0x0 0x0 0x0 0x0) so
that the decryptor doesn't accidentally remove something it wasn't supposed to.
You can now implement a des_encrypt routine, as shown in Listing 2-16,
that uses des_block_operate after padding its input to encrypt an arbitrarily
sized block of text.
Listing 2-16: “des.c” des_operate with padding support
static void des_operate( const unsigned char *input,
int input_len,
unsigned char *output,
const unsigned char *key,
op_type operation )
{
unsigned char input_block[ DES_BLOCK_SIZE ];
assert( !( input_len % DES_BLOCK_SIZE ) );
while ( input_len )
{
memcpy( ( void * ) input_block, ( void * ) input, DES_BLOCK_SIZE );
des_block_operate( input_block, output, key, operation );
input += DES_BLOCK_SIZE;
output += DES_BLOCK_SIZE;
input_len -= DES_BLOCK_SIZE;
}
}
 
Search WWH ::




Custom Search