Sign And Encrypt With OpenSSL

Kevin FOO
1 min readNov 30, 2023

Alice has a keypair, alice_private.pem and alice_public.pem
Bob has a keypair, bob_private.pem and bob_public.pem
Please refer to asymmetric encryption if you would like to generate key pair.

Alice sends Bob alice_public.pem
Hence Bob owns
1) bob_private.pem
2) bob_public.pem
3) alice_public.pem

Bob sends Alice bob_public.pem
Hence Alice owns
1) alice_private.pem
2) alice_public.pem
3) bob_public.pem

Alice would like to send a signed encrypted file to Bob. To sign plain.txt, Alice needs to

openssl dgst -sha256 -sign alice_private.pem -out sha256.sig plain.txt

To encrypt, Alice needs to

openssl pkeyutl -encrypt -inkey bob_public.pem -pubin -in plain.txt -out encrypted.enc

Alice then sends to Bob these files
1) encrypted.enc
2) sha256.sig
To decrypt, Bob needs to

openssl pkeyutl -decrypt -inkey bob_private.pem -in encrypted.enc > decrypted.txt

Bob now has decrypted.txt, but is it really from Alice? To verify, Bob needs to

openssl dgst -sha256 -verify alice_public.pem -signature sha256.sig decrypted.txt

The encrypted file and the signature are both in binary format. To encode binary file to base64

openssl base64 -in encrypted.bin -out encrypted.b64

To decode base64 file back to binary

openssl base64 -d -in encrypted.b64 -out encrypted.bin

< Back to all the stories I had written

--

--

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.