4

I try to encrypt simple text with RSA algorithm. I have a problem with my code.

RSA        *_RSA ;
unsigned char text[2560] = "A";
unsigned char sectext[2560];
unsigned char decrypttext[2560];
int i = 0;

_RSA = RSA_generate_key ( 1024, 65537, NULL, NULL );
i = RSA_public_encrypt ( 1, text,    sectext,     _RSA, RSA_PKCS1_OAEP_PADDING );
i = RSA_private_decrypt( 1, sectext, decrypttext, _RSA, RSA_PKCS1_OAEP_PADDING);
RSA_free ( _RSA );

The return value of RSA_public_encrypt is 128, which is the size of the ciphertext. RSA_private_decrypt returns -1, which is an error. If I try to display the recovered text then I get nothing.

Why is RSA_private_decrypt returning -1?

jww
  • 97,681
  • 90
  • 411
  • 885
  • 1
    _RSA not a good idea: see http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier#228797 – Martin York Jan 08 '09 at 23:47

2 Answers2

8

You should not pass 1 to RSA_private_decrypt but the length of the block you are trying to decrypt, ie. the return value of RSA_public_encrypt = 128. You do not know the length of the cleartext when you are decrypting!

This complete sample program results in:

128 from encrypt. 
1 from decrypt: 'A'

Source:

#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    RSA *myRSA;
    unsigned char cleartext[2560] = "A";
    unsigned char encrypted[2560] = { 0 };
    unsigned char decrypted[2560] = { 0 };
    int resultEncrypt = 0;
    int resultDecrypt = 0;

    myRSA = RSA_generate_key ( 1024, 65537, NULL, NULL );
    resultEncrypt = RSA_public_encrypt ( 1 /* strlen(cleartext) */, cleartext, encrypted, myRSA, RSA_PKCS1_OAEP_PADDING );
    printf("%d from encrypt.\n", resultEncrypt);
    resultDecrypt = RSA_private_decrypt( 128 /* resultEncrypt */, encrypted, decrypted, myRSA, RSA_PKCS1_OAEP_PADDING);
    printf("%d from decrypt: '%s'\n", resultDecrypt, decrypted);
    RSA_free ( myRSA );

    return 0;
}
Tuminoid
  • 9,445
  • 7
  • 36
  • 51
0

Try calling ERR_error_string() to get a text description of the error.

Andreas Magnusson
  • 7,321
  • 3
  • 31
  • 36