openssl public key encryption

07 Apr 2012



If one wants to encrypt aribtrary data or a file using public key encryption algorithms, one can use OpenSSL and S/MIME.



For algorithms and key sizes, the NIST Computer Security Division says 2048-key for RSA and 128-bit key for AES is just fine until 2030 (Special Publication 800-57, page 66).



The examples below all use stdin and stdout.  You can use files by using "-in INFILE -out OUTFILE" on the command line.





# create 2048 bit key

openssl req -x509 -nodes -newkey rsa:2048 </span>

    -keyout PRIVATE1.pem </span>

    -out PUBLIC1.pem </span>

    -subj '/'




# encrypt, note that it is different each time

echo "client9.com" | </span>

   openssl smime -encrypt -aes128 -binary -outform DEM PUBLIC1.pem | </span>

   base64

echo "client9.com" | </span>

   openssl smime -encrypt -aes128 -binary -outform DEM PUBLIC1.pem | </span>

   base64




# and decrypt

echo "client9.com" | </span>

  openssl smime -encrypt -aes128 -binary -outform DEM PUBLIC.pem | </span>

  openssl smime -decrypt -binary -inform DEM -inkey PRIVATE.pem 




# let's create another key

openssl req -x509 -nodes  -newkey rsa:2048 </span>

    -keyout PRIVATE2.pem </span>

    -out PUBLIC2.pem </span>

    -subj '/'






# we can now encrypt with both public keys

# and then use either private key to decrypt

# (can use as many keys as you want)

#

echo "client9.com" | </span>

   openssl smime -encrypt -aes128 -binary -outform DEM </span>

   PUBLIC1.pem PUBLIC2.pem | </span>

   base64




# let's use key #1 to decrypt

echo "client9.com" | </span>

   openssl smime -encrypt -aes128 -binary -outform DEM </span>

   PublicCert1.pem PublicCert2.pem | </span>

   openssl smime -decrypt -binary -inform DEM  -inkey PRIVATE1.pem




# let's use key #2 to decrypt

echo "client9.com" | </span>

   openssl smime -encrypt -aes128 -binary -outform DEM </span>

   PublicCert1.pem PublicCert2.pem | </span>

   openssl smime -decrypt -binary -inform DEM  -inkey PRIVATE2.pem 




# snazzy!


Using Raw RSA



I wrote this article since the first few Google results for "openssl public key encryption" all used raw RSA.  Eeek.  If your data is always smaller than the key size (minus some overhead), you could use raw RSA but must make sure you use OAEP padding schemes (the older PKCS padding is probably ok, but maybe not given you have a "small input" probably with a known structure).  Do not try and create some RSA-CBC hybrid beast.  Use S/MIME instead.






# generate keypair


openssl genrsa -out private.pem 2048





# extract public key


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





# decrypt


echo "client9.com" | </span>


   openssl rsautl -encrypt -oaep -inkey public.pem -pubin | </span>


   openssl rsautl -decrypt -inkey private.pem





# please check the maximum input size first!