Learn more about Russian war crimes in Ukraine.

How can I do elliptic curve crypto with OpenSSL?

I’ve previously looked at doing asymmetric crypto with openssl using the genrsa, rsa, and rsautl commands. This uses RSA, which is one way to do asymmetric crypto. An alternative way is elliptic-curve crypto (ECC), and openssl has commands for ECC too.

Here’s how Alice and Bob generate their private keys and extract public keys from them:

# Alice generates her private key
openssl ecparam -name secp256k1 -genkey -noout -out alice_priv_key.pem

# Alice extracts her public key from her private key
openssl ec -in alice_priv_key.pem -pubout -out alice_pub_key.pem

(Here, we choose the curve secp256k1. There are many to choose from.)

However, there are no tools for encrypting and decrypting! ECC doesn’t define these directly. Instead, ECC users use Diffie-Hellman (DH) key exchange to compute a shared secret, then communicate using that shared secret. This combination of ECC and DH is called ECDH.

See Alice and Bob derive their shared secret:

$ openssl pkeyutl -derive -inkey alice_priv_key.pem -peerkey bob_pub_key.pem -out alice_shared_secret.bin
$ openssl pkeyutl -derive -inkey bob_priv_key.pem -peerkey alice_pub_key.pem -out bob_shared_secret.bin
$ base64 alice_shared_secret.bin
BvqYFmmnn7s9M8bOrO0YDmBHs1sBIAtz5/0mmCQY5/8=
$ base64 bob_shared_secret.bin
BvqYFmmnn7s9M8bOrO0YDmBHs1sBIAtz5/0mmCQY5/8=

Notice Alice’s shared secret file is the same as Bob’s. They can now use this shared secret to communicate using any symmetric crypto. For example:

$ echo 'I love you Bob' > plain.txt
$ openssl enc -aes256 -base64 -k $(base64 alice_shared_secret.bin) -e -in plain.txt -out cipher.txt
$ openssl enc -aes256 -base64 -k $(base64 bob_shared_secret.bin) -d -in cipher.txt -out plain_again.txt
$ cat plain_again.txt
I love you Bob

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.