Public Key Cryptography with OpenSSL

Suresh Attanayake
sureshatt
Published in
2 min readApr 5, 2020

OpenSSL is a swiss army knief when it come to cryptographic operations such as SSL certificate generations, SSL troubleshooting, hashing and other crypto operations. It comes with various and sometime overlapping tools for crypto graphic operations, however in this article we are focusing only on the genpkey, pkey and pkeyutil tools to generate a private-public keypair and to validate them.

Step1: Generate a keypair using “genpkey”

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:1028 -outform pem -out rsakey.pem -aes192
  • -algorithm: RSA, ECDSA, DSA, DFH are supported
  • -pkeyopt can be used to further configure the key generation.
  • -outform defines the exported file format. The PEM or the DER format can be defined.
  • -aes192 signals OpenSSL to encrypt the private key using a provided password. After running above command, OpenSSL will prompt for password. However password can also be fed using the -pass parameter. For example:
-pass pass:plaintextpassword (providing as a plaintext password)
-pass env:env_variable_key_password (providing as an environment variable)
-pass file:_path_to_file

Step 2: Extract public key using “pkey”

The the generated private key is PKCS#8 compliant. That is, the file itself contain both private key and public key. Hence we can retried the public key from the file using the pkey tool.

openssl pkey -in rsakey.pem -out rsapubkey.pem -outform pem -pubout
  • -pubout signals OpenSSL to export the public key, but not the private key.

Note: The pkey tool can be used to convert private key from one format to the other. For example the PEM format private key can be then converted to DER or P8. For example, converting to P8:
openssl pkcs8 -in rsakeys.pem -inform pem -out rsakeys.p8 -topk8

Step 3: Sign with the private key using “pkeyutl”

Create a text file called data.txt

openssl pkeyutl -sign -in data.txt -inkey rsakey.pem -out sigdata.txt

Step 4: Signature verification with the public key using “pkeyutl”

openssl pkeyutl -verify -pubin -inkey rsapubkey.pem -sigfile sigdata.txt -in data.txt

Step 5: Encrypt with the public key using “pkeyutl”

openssl pkeyutl -encrypt -pubin -inkey rsapubkey.pem -in data.txt -out encdata.txt

Step 6: Decrypt with the private key using “pkeyutl”

openssl pkeyutl -decrypt -inkey rsakey.pem -in encdata.txt -out decdata.txt

--

--