How to encrypt using a private key file generated by OpenSSL?

Do not use the OpenSSL command line to encrypt or sign anything. The OpenSSL command line is a debugging tool. To encrypt or sign a message, use a tool designed for this purpose, such as GPG.

A private key file contains all the information needed to construct the public key. If you have a private key in a format that OpenSSL understands and you want to get the corresponding public key, you can use openssl pkey -pubout …. But that's not the format GPG needs. GPG generates its own keys.


The private key is used to decrypt, and to sign things. You don't use it to encrypt. You use the public key for that. But openssl genrsa will not generate the public key, only the private. To encrypt things, you must first generate the public key (so you have a keypair: private and public):

openssl rsa -in yourdomain.key -outform PEM -pubout -out public.pem

This will create public.pem file with, well, the public key. Use it to encript the file:

openssl rsautl -encrypt -inkey public.pem  -pubin -in file.txt -out file.enc

To decrypt later, you use the private key:

openssl rsautl -decrypt -inkey yourdomain.key -in file.enc  -out file.dec