How Do We Generate a Base64-Encoded SHA256 Hash of SubjectPublicKeyInfo of an X.509 Certificate, for Android N Certificate Pinning?

openssl x509 -in cert.crt -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64

You may need to add -inform der to the first command if cert.crt is in DER form rather than in PEM form.


For setting up Android network-security-config pinning for a host that is already live, I prefer gnutls-cli (GnuTLS Client). It outputs a host's certificate info in a form where the sha256 is readibly copy-pasteable as base64 encoded. For example:

$ gnutls-cli stackoverflow.com </dev/null
<...>
 - subject `CN=*.stackexchange.com,O=Stack Exchange\, Inc.,L=New York,ST=NY,C=US', issuer `CN=DigiCert SHA2 High Assurance Server CA,OU=www.digicert.com,O=DigiCert Inc,C=US', serial 0x0e11bbd70d54b710d0c6f540b6b52ca4, RSA key 2048 bits, signed using RSA-SHA256, activated `2016-05-21 00:00:00 UTC', expires `2019-08-14 12:00:00 UTC', pin-sha256="2zKehMv7KtnGBz1d2U0bFrAOKb1aWWlrG9a0BzrOvwA="