Cryptography Reference
In-Depth Information
des_operate iterates over the input, calling des_block_operate on each eight-
byte block. The caller of des_operate is responsible for padding to ensure that
the input is eight-byte aligned, as shown in Listing 2-17.
Listing 2-17: “des.c” des_encrypt with NIST 800-3A padding
void des_encrypt( const unsigned char *plaintext,
const int plaintext_len,
unsigned char *ciphertext,
const unsigned char *key )
{
unsigned char *padded_plaintext;
int padding_len;
// First, pad the input to a multiple of DES_BLOCK_SIZE
padding_len = DES_BLOCK_SIZE - ( plaintext_len % DES_BLOCK_SIZE );
padded_plaintext = malloc( plaintext_len + padding_len );
// This implements NIST 800-3A padding
memset( padded_plaintext, 0x0, plaintext_len + padding_len );
padded_plaintext[ plaintext_len ] = 0x80;
memcpy( padded_plaintext, plaintext, plaintext_len );
des_operate( padded_plaintext, plaintext_len + padding_len, ciphertext,
key, OP_ENCRYPT );
free( padded_plaintext );
}
The des_encrypt variant shown in Listing 2-17 fi rst fi gures out how much
padding is needed — it will be between one and eight bytes. Remember, if the
input is already eight-byte aligned, you must add a dummy block of eight bytes
on the end so that the decryption routine doesn't remove valid data. des_encrypt
then allocates enough memory to hold the padded input, copies the original
input into this space, sets the fi rst byte of padding to 0x80 and the rest to 0x0
as described earlier.
Another approach to padding, called PKCS #5 padding, is to append the
number of padding bytes as the padding byte. This way, the decryptor can just
look at the last byte of the output and then strip off that number of bytes from
the result (with 8 being a legitimate number of bytes to strip off). Using the
“abcdef” example again, the padded input now becomes
61 62 63 64 65 66 02 02
a b c d e f
Because two bytes of padding are added, the number 2 is added twice. If the
input was “abcde,” the padded result is instead.
 
Search WWH ::




Custom Search