Cryptography Reference
In-Depth Information
( array[ ( int ) ( bit / 8 ) ] |= ( 0x80 >> ( bit % 8 ) ) )
#define CLEAR_BIT( array, bit ) \
( array[ ( int ) ( bit / 8 ) ] &= ~( 0x80 >> ( bit % 8 ) ) )
Although this is a bit dense, you should see that
GET_BIT
returns 0 if an array
contains a 0 at a specifi c bit position and non-zero if an array contains a 1. The
divide operator selects the byte in the array, and the shift and mod operator
selects the bit within that byte.
SET_BIT
and
CLEAR_BIT
work similarly, but actu-
ally update the position. Notice that the only difference between these three
macros is the operator between the array reference and the mask:
&
for get,
|=
for set, and
&= ~
for clear.
Because this example XORs entire arrays of bytes, you need a support routine
for that as shown in Listing 2-2.
Listing 2-2:
“des.c” xor array
static void xor( unsigned char *target, const unsigned char *src, int len )
{
while ( len-- )
{
*target++ ^= *src++;
}
}
This overwrites the target array with the XOR of it and the
src
array.
Finally, you need a permute routine. The permute routine is responsible
for putting, for instance, the 57
th
bit of the input into the 14
th
bit of the output,
depending on the entries in a
permute_table
array. As you'll see in the code
listings that follow, this function is the workhorse of the DES algorithm; it is
called dozens of times, with different
permute_tables
each time.
Listing 2-3:
“des.c” permutation
/**
* Implement the initial and final permutation functions. permute_table
* and target must have exactly len and len * 8 number of entries,
* respectively, but src can be shorter (expansion function depends on this).
* NOTE: this assumes that the permutation tables are defined as one-based
* rather than 0-based arrays, since they're given that way in the
* specification.
*/
static void permute( unsigned char target[],
const unsigned char src[],
const int permute_table[],
int len )
{
int i;
for ( i = 0; i < len * 8; i++ )
(Continued)
Search WWH ::
Custom Search