get SHA256 hash of public key
Asked Answered
N

3

16

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?

Nerti answered 19/3, 2018 at 14:26 Comment(1)
See #9607795 for obtaining the SHA256 of a public key if it's not in a .pem file.Nitrile
F
18

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)

Faletti answered 5/2, 2020 at 16:46 Comment(1)
Hm. Interesting, I don't get the same results via ssh-keygen as via openssl (or the very clever approach shown by @just-be-happy) — I wonder why that is.Apps
A
10

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
Aragonite answered 19/3, 2018 at 14:42 Comment(5)
@Nerti Are you sure you executed the command in the same folder where the file pubkey.pem was created?Aragonite
Yes, I am sure. It also outputroutines:PEM_read_bio:no start line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22/libressl/crypto/pem/pem_lib.c:704Nerti
Hmm... actually, the problem is the certificate and public key I generated has 0 size. Something wrong there....Nerti
@Nerti 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,Aragonite
I am fixing it, will get back to you here. Thanks!Nerti
T
1

You can try directly decode public key with base64, then pipe to shasum -a256or 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
Thomasina answered 22/3, 2023 at 9:17 Comment(1)
Heh. Magic! :-) In my case, I didn't have a full certificate — but just the public key! — and openssl complained and grumbled but spewed something out. Not by coincidence, it was exactly the same SHA256 as produced with your (adapted) command: cat mypubkey.pem | sed '1d;$d' | base64 -d | shasum -a256. (or sha256sum -b — same thing). "Hey Ma! No openssl command!" 😂Apps

© 2022 - 2024 — McMap. All rights reserved.