How to encrypt and decrypt with RSA on the command line
The openssl
tool provides two subcommands for encrypting with RSA – pkeyutl
and the deprecated, RSA-specific rsautl
subcommand. We will, of course, use pkeyutl
. Documentation for that subcommand can be found on the openssl-pkeyutl
man page:
man openssl-pkeyutl
As explained previously, RSA is usually used for encrypting a session key, which will then be used to encrypt useful data. Let’s generate a 256-bit session key:
$ openssl rand -out session_key.bin 32
Now, let’s use openssl pkeyutl
with our public RSA key for encrypting the session key:
$ openssl pkeyutl \ -encrypt \ -in session_key.bin \ -out session_key.bin.encrypted \ -pubin \ -inkey rsa_public_key.pem \ -pkeyopt rsa_padding_mode:oaep
Note the -pkeyopt rsa_padding_mode:oaep
switch. It instructs...