RSA - relation between message size and key size

Steffen Bingel, pi4 sbi at pi4.de
Tue Jun 26 16:06:24 CEST 2018


Hi,

at first, this is the first time for me using a mailing list and I 
apologize in advance for any violation of rules I may not know yet.

I'm playing around with the private/public key functions of libgcrypt 
and ran into an behavior I couldn't find an explanation for. If my 
message that I try to encrypt is larger than the key I use for 
encryption the pk_encrypt seems to generate random data without throwing 
an error. The following code is a condensed copy from 
https://github.com/vedantk/gcrypt-example/blob/master/main.cc. If my 
message contains 32 characters (256 bit) this works fine but if I pass 
33 or more characters the decrypted messages makes no sense at all. I 
was also playing around with bigger keys where I could observe the same 
behavior (msg bigger than key not working).

So if the function is not intended to take data larger than the key, why 
is it not returning an error?

What is the correct way to encrypt large, at least larger than the key, 
binary data I have in memory?

Thanks a lot

     gcry_error_t err;

     #define _assert(cmd) {\
         err = cmd;\
         if (err != GPG_ERR_NO_ERROR) {\
             L("ERR: command returned: %s",gcry_strerror(err));\
         }}

     /* generate key pair */
     gcry_sexp_t rsa_keypair;
     gcry_sexp_t parms;
     _assert(gcry_sexp_build( &parms, NULL, "(genkey(rsa(nbits %d)))",256));

     _assert(gcry_pk_genkey( &rsa_keypair,parms ));

     gcry_sexp_t pubk = gcry_sexp_find_token(rsa_keypair, "public-key", 0);
     gcry_sexp_t privk = gcry_sexp_find_token(rsa_keypair, 
"private-key", 0);

     /* Create a message. */
     gcry_mpi_t msg;
     gcry_sexp_t data;
     const unsigned char* s = (const unsigned char*)
         "uweoirdnd1iejfkslrm2kdleirjfm3xss";
     _assert(gcry_mpi_scan(&msg, GCRYMPI_FMT_USG, s, strlen((const 
char*) s), NULL));

     gcry_mpi_dump(msg);

     _assert(gcry_sexp_build(&data, NULL,"(data (flags raw) (value 
%m))", msg));

     gcry_sexp_dump(data);

     /* Encrypt the message. */
     gcry_sexp_t ciph;
     _assert(gcry_pk_encrypt(&ciph, data, pubk));

     gcry_sexp_dump(ciph);

     /* Decrypt the message. */
     gcry_sexp_t plain;
     _assert(gcry_pk_decrypt(&plain, ciph, privk));

     /* Pretty-print the results. */
     gcry_mpi_t out_msg = gcry_sexp_nth_mpi(plain, 0, GCRYMPI_FMT_USG);
     L("Original:");
     gcry_mpi_dump(msg);
     L("\n" "Decrypted:");
     gcry_mpi_dump(out_msg);

     if (gcry_mpi_cmp(msg, out_msg)) {
         L("data corruption!");
     } else {
         L("Messages match.\n");
     }







More information about the Gcrypt-devel mailing list