Generating EC keys with OpenSSL

Tips on how to generate EC keys with openssl command line tool.

When creating a JWT (JSON Web Token), there are many algorithms for signing the signature. For digital signatures using the ECDSA algorithm, you need an EC key to sign the signature. Here are the algorithms defined by RFC7518 section 3.4 that MUST use an EC key:

  • ES256: ECDSA using P-256 and SHA-256
  • ES384: ECDSA using P-384 and SHA-384
  • ES512: ECDSA using P-521 and SHA-512

It is very easy to generate an EC key using openssl. But if you are not familiar with openssl, here are some commands that you can just copy and use. I assume you have openssl installed.

Note

You can use joserfc to generate EC keys: https://jose.authlib.org/en/dev/recipes/openssl/

EC key with crv P-256

This key can be used for the alg: ES256, the commands below will generate the private and public keys:

# generate a private key
openssl ecparam -name prime256v1 -genkey -noout -out ec-p256-private.pem

# extract the public key
openssl ec -in ec-p256-private.pem -pubout -out ec-p256-public.pem

Note: OpenSSL encourages using prime256v1 instead of secp256r1.

EC key with crv P-384

This key can be used for alg: ES384:

# generate a private key
openssl ecparam -name secp384r1 -genkey -noout -out ec-p384-private.pem

# extract the public key
openssl ec -in ec-p384-private.pem -pubout -out ec-p384-public.pem

EC key with crv P-512

This key can be used for alg: ES512:

# generate a private key
openssl ecparam -name secp521r1 -genkey -noout -out ec-p512-private.pem

# extract the public key
openssl ec -in ec-p512-private.pem -pubout -out ec-p512-public.pem

Note: It is secp521r1, not secp512r1. But the "crv" value in EC Key is "P-512".

EC key with crv secp256k1

This key is used for ECDSA Signature with secp256k1 Curve defined by RFC8812.

  • ES256K: ECDSA using secp256k1 and SHA-256
# generate a private key
openssl ecparam -name secp256k1 -genkey -noout -out ec-secp256k1-private.pem

# extract the public key
openssl ec -in ec-secp256k1-private.pem -pubout -out ec-secp256k1-public.pem