Cryptography Reference
In-Depth Information
Due to the way padding works, it's diffi cult for the caller to fi gure out
how much space the decrypted data takes up (a one-byte payload could
encrypt to a 256-byte value!). As a result, listing 3-21 allocates space in
the target output array.
Listing 3-21: “rsa.c” rsa_encrypt
/**
* The input should be broken up into n-bit blocks, where n is the
* length in bits of the modulus. The output will always be n bits
* or less. Per RFC 2313, there must be at least 8 bytes of padding
* to prevent an attacker from trying all possible padding bytes.
*
* output will be allocated by this routine, must be freed by the
* caller.
*
* returns the length of the data encrypted in output
*/
int rsa_encrypt( unsigned char *input,
unsigned int len,
unsigned char **output,
rsa_key *public_key )
{
int i;
huge c, m;
int modulus_length = public_key->modulus->size;
int block_size;
unsigned char *padded_block = ( unsigned char * )
malloc( modulus_length );
int encrypted_size = 0;
*output = NULL;
while ( len )
{
encrypted_size += modulus_length;
block_size = ( len < modulus_length - 11 ) ?
len : ( modulus_length - 11 );
memset( padded_block, 0, modulus_length );
memcpy( padded_block + ( modulus_length - block_size ),
input, block_size );
// set block type
padded_block[ 1 ] = 0x02;
for ( i = 2; i < ( modulus_length - block_size - 1 ); i++ )
{
// TODO make these random
padded_block[ i ] = i;
}
(Continued)
 
Search WWH ::




Custom Search