Cryptography Reference
In-Depth Information
do; you'd expect that it would be trivial to extend this out to larger numbers.
However, when dealing with arbitrarily-sized numbers, you must deal with
inputs of differing sizes and the possibility of overfl ow. A large-number add
routine is shown in Listing 3-2.
Listing 3-2: “huge.c” add routine
/**
* Add two huges - overwrite h1 with the result.
*/
void add( huge *h1, huge *h2 )
{
unsigned int i, j;
unsigned int sum;
unsigned int carry = 0;
// Adding h2 to h1. If h2 is > h1 to begin with, resize h1.
if ( h2->size > h1->size )
{
unsigned char *tmp = h1->rep;
h1->rep = ( unsigned char * ) calloc( h2->size,
sizeof( unsigned char ) );
memcpy( h1->rep + ( h2->size - h1->size ), tmp, h1->size );
h1->size = h2->size;
free( tmp );
}
i = h1->size;
j = h2->size;
do
{
i--;
if ( j )
{
j--;
sum = h1->rep[ i ] + h2->rep[ j ] + carry;
}
else
{
sum = h1->rep[ i ] + carry;
}
carry = sum > 0xFF;
h1->rep[ i ] = sum;
}
while ( i );
if ( carry )
{
 
Search WWH ::




Custom Search