[Botan-devel] Trying to pass a RSA key from memory to RSA Private

Jack Lloyd lloyd at randombit.net
Fri Jun 11 17:06:22 EDT 2010

On Fri, Jun 11, 2010 at 01:21:43PM -0700, Pete Toich wrote:

> 1. opens a public key file using the X509 part of the API
> 2. reads the private key into memory
> 3. loads the private key via the memory source
> 4.  decrypts the data
> 5.  compares

The problem is here:

>         decrypted_data = rsakey->decrypt( 
>                 encrypted_data,
>                 sizeof(test_data) );
>         printf("%s, %i: Decrypted data:\n", __FILE__, __LINE__ );
>         display_hex_data( decrypted_data, sizeof(test_data) );

The encrypted_data will not be the same size as the input
(sizeof(test_data)), but rather be (roughly) the size of the RSA
modulus. You'd want to use encrypted_data.size() and
decrypted_data.size(), respectively for these two uses of sizeof().

However even that won't fix your issue perfectly, because after
you make this change you'll see:

test_rsa.cpp, 138: Original data:
 0,  4,  1,  8,  2,  c,  3, 10,  4, 14,  5, 18,  6, 1c,  7, 20,
test_rsa.cpp, 192: Decrypted data:
 4,  1,  8,  2,  c,  3, 10,  4, 14,  5, 18,  6, 1c,  7, 20,
test_rsa.cpp, 207: Data miscompare at location 0, exp: 0x00, act: 0x04

This is the same problem discussed in this thread:


Basically, RSA only encrypts integers; so when it converts your
bitstring input into an integer, the leading zero vanishes, and the
decrypting side doesn't know to add it (for all the decrypting key
knows, there were originally 0, 3, or 15 leading zeros on the
plaintext). There are various padding schemes which have a number of
useful properties, including framing the message so that it can be
unambigiously encoded and decoded even in the presence of things like
leading 0s in the message.

What you need to do is use a PK_Encryptor class, which knows how
to combine a base scheme like RSA with a padding algorithm. There
are some examples in doc/examples/rsa*, but the short version is:

  PK_Encryptor_MR_with_EME encryptor(rsa_public_key, "EME1(SHA-1)");

  encrypted_data = encryptor.encrypt((Botan::byte *)&test_data,

  PK_Decryptor_MR_with_EME decryptor(rsa_private_key, "EME1(SHA-1)");

   You don't need to explicitly specify the length here because
   this function knows how to find the length of a SecureVector
  decrypted_data = decryptor.decrypt(encrypted_data);

EME1 is sometimes called OAEP; it's a standard encoding that is
supported by most all crypto libraries.


More information about the botan-devel mailing list