I have a certificate mycert.pem
. I got the public key of the certificate by command:
openssl x509 -pubkey -noout -in mycert.pem > pubkey.pem
How can I get the SHA256 hash of the public key?
I have a certificate mycert.pem
. I got the public key of the certificate by command:
openssl x509 -pubkey -noout -in mycert.pem > pubkey.pem
How can I get the SHA256 hash of the public key?
You can use ssh-keygen. Convert file format first
ssh-keygen -i -m PKCS8 -f pubkey.pem > NEWpubkey.pem
Next get the fingerprint
ssh-keygen -lf NEWpubkey.pem
Get type inference
2048 SHA256:hYAU9plz1WZ+H+eZCushetKpeT5RXEnR8e5xsbFWRiU no comment (RSA)
The openssl -pubkey
outputs the key in PEM format (even if you use -outform DER
).
Assuming you have a RSA public key, you have to convert the key in DER format (binary) and then get its hash value:
openssl rsa -in pubkey.pem -pubin -outform der | openssl dgst -sha256
You can try directly decode public key with base64, then pipe to shasum -a256
or openssl sha256
to get the hash you want:
sed '1d;$d' ./pubkey.pem | base64 -D | openssl sha256 # or shasum -a256
If you use command question mentioned to output pubkey.pem like:
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
You need strip first and last line in advance like sed '1d;$d'
.
Then we use base64 -d
or -D
to decode (default to stdout) and pipe to openssl sha256
.
All in one command:
sed '1d;$d' <(openssl x509 -pubkey -noout -in mycert.pem) | base64 -D | openssl sha256