2

I am experimenting with using libtomcrypt to do RSA-2048 bit encryption. My current objective is to import a public key from a file. This file was generated using OpenSSL with the command:

$ openssl rsa -in private.pem -outform PEM -pubout -out public.pem

So I believe my public key is in PKCS#1 padding and in OpenSSL's PEM format.

I believe the function I need to use is rsa_import(), but that takes an in buffer, a length, and outputs an rsa_key pointer. Just to be clear, I believe what I need to do is as follows:

  1. Read in the contents of public.pem to a buffer
  2. Toss out the Header and Footers containing "Begin Public Key" etc.
  3. Decode data from base64.
  4. Pass in resulting data to rsa_import.

Is this correct? Can anyone who has used libtomcrypt for this purpose comment on this? Thanks.

HD_Mouse
  • 567
  • 1
  • 7
  • 19

1 Answers1

2

So, upon digging into the source of rsa_import(), I figured out pretty quickly that it was expecting the key to be in DER format. Since I had access to the private key, I just made a DER file using this openssl command:

openssl rsa -in private.pem -outform DER -pubout -out public.der

Notably the argument for -outform is now DER rather than PEM. After this, I just read the file contents into a char buffer, then passed that in as the main argument for rsa_import. After that rsa_import made the key no problem and I was able to encrypt/decrypt from there.

HD_Mouse
  • 567
  • 1
  • 7
  • 19
  • Did you kept the 4 steps that appear in the question? – Alex Feb 02 '17 at 12:08
  • This is instead of the 4 steps above. As it is one step, it is less error prone (and more likely to work). The steps should be equivalent. Note, there are two forms of RSA keys. You can use '-pubout' for pkcs#5 or '-RSAPublic_out' for pkcs#1. In each case, libtomcrypt wants the DER format. You can generate the key directly with `-outform DER` as the answer suggests. The 4 step method will produce the same output, if done correctly. – artless noise May 09 '23 at 20:14