已导出证书公钥至pubkey.pem,如何获取其SHA256哈希值?
Hey there! Let's walk through how to get the SHA256 hash of your exported public key pubkey.pem. There are a couple of straightforward ways to do this with OpenSSL, depending on exactly what you need:
Option 1: Hash the entire PEM file (including headers/footers)
If you just want the SHA256 hash of the actual pubkey.pem file as-is (which includes the -----BEGIN PUBLIC KEY-----/-----END PUBLIC KEY----- headers and any whitespace), run this command:
openssl dgst -sha256 pubkey.pem
You'll get output that looks like:
SHA2-256(pubkey.pem)= a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2
Option 2: Hash the raw public key data (most common use case)
In most scenarios, you'll want the hash of the actual public key material (stripping away the PEM formatting). To do this, first convert the PEM public key to DER format (the raw binary encoding), then compute the SHA256 hash:
openssl pkey -pubin -in pubkey.pem -outform der | openssl dgst -sha256
Or if you prefer the hash in plain hexadecimal without the prefix, add the -hex flag and pipe to awk to extract just the hash string:
openssl pkey -pubin -in pubkey.pem -outform der | openssl dgst -sha256 -hex | awk '{print $2}'
This will give you something like:
a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2
A quick note: The pkey command is more versatile than rsa here because it works with all public key types (not just RSA). If you know your key is definitely RSA, you could replace pkey with rsa and it would work the same, but pkey is safer for general use.
内容的提问来源于stack exchange,提问作者Leem

