How to find out if a certificate has an elliptic curve or an RSA key
You can use openssl
to find out if your certificate is using an elliptic curve (e.g. ECDSA) or an RSA key using the following command, replacing cert.pem
by the path of your certificate:
openssl x509 -noout -text -in cert.pem | grep -i "ecPublicKey" > /dev/null ; if [ $? -ne 0 ]; then echo "No elliptic curve key" ; else echo "Elliptic curve key"; fi
If the certficate’s key is an elliptic curve key, it will print:
Elliptic curve key
If the certficate’s key another type of key like a RSA key, it will print:
No elliptic curve key
How it works
First we tell OpenSSL to print info about the certificate:
openssl x509 -noout -text -in cert.pem
Then we grep for ecPublicKey
. This is because for elliptic curve keys, the output of the aforementioned openssl
command contains
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (384 bit)
pub:
whereas for RSA keys it looks like this:
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
The grep
command is piped to /dev/null
since we’re not interested in its output but only in its return code (which is available as $?
in the shell). grep
returns a return code of 0
if and only if it finds at least one match in the input. Otherwise, it has a return code of 1
. In our case, this means that we’ll get a return code of 0
if ecPublicKey
appears anywhere in the output. We assume that this string will only ever occur in the Subject Public Key Info:
section. While in theory it is possible that ecPublicKey
appears in some user-defined fields of the certificate, this is extremely unlikely to happen and could be mitigated by using a regular expression in grep
We can then use this bash
snippet:
if [ $? -ne 0 ]
then
# TODO insert code if grep does NOT find anything
else
# TODO insert code if grep finds at least one line
fi
which we use like this:
if [ $? -ne 0 ]; then echo "No elliptic curve key" ; else echo "Elliptic curve key"; fi
i.e. depending on the return code of grep
, we will print the correct message.