10

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?

Leem
  • 15,772
  • 32
  • 101
  • 149
  • See https://stackoverflow.com/questions/9607295/calculate-rsa-key-fingerprint for obtaining the SHA256 of a public key if it's not in a `.pem` file. – aleb Apr 01 '20 at 11:47

3 Answers3

9

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)

uanr81
  • 101
  • 1
  • 7
7

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
oliv
  • 11,964
  • 22
  • 40
  • @Leem Are you sure you executed the command in the same folder where the file `pubkey.pem` was created? – oliv Mar 19 '18 at 14:45
  • Yes, I am sure. It also output`routines:PEM_read_bio:no start line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/pem/pem_lib.c:704` – Leem Mar 19 '18 at 14:51
  • Hmm... actually, the problem is the certificate and public key I generated has 0 size. Something wrong there.... – Leem Mar 19 '18 at 14:53
  • @Leem So this means that the command `openssl x509 -pubkey -noout -in mycert.pem` didn' t work. Please fix your certificate and give feedback on the command I posted, – oliv Mar 19 '18 at 15:20
  • I am fixing it, will get back to you here. Thanks! – Leem Mar 19 '18 at 15:30
-3

You can either:

generate sha256sum directly from certificate file, using this command:

openssl x509 -pubkey -noout -in <your-certificate-filename>.pem | openssl dgst -sha256

or

generate public key of your certificate using this simple command:

openssl x509 -pubkey -noout -in <your-certificate-filename>.pem > <public-key-filename>.pem

And verify it using this command:

cat <public-key-filename>.pem | sha256sum

Vahid F
  • 325
  • 6
  • 16