如何从 X.509 证书中获取十六进制格式的 public 密钥

How to get public key in hex format from a X.509 certificate

是否可以通过openssl只获取十六进制格式的public密钥?我使用了命令:

openssl x509 -in a.pem -text -noout

这只是打印证书,其中 public 密钥以十六进制格式提供,但我无法解析它。例如这个命令:

openssl x509 -in a.pem -pubkey -noout

returns public 密钥格式如下:

-----BEGIN PUBLIC KEY-----
#######
####===
-----END PUBLIC KEY----

有更好的方法吗?我期待十六进制格式的输出。

由于(经过讨论)它是一个已经采用 Base64(装甲 ASCII)格式的自签名密钥,因此像 tomeko.net 这样的工具足以将其编码为十六进制。


原回答:

来自 this article,对于受信任的证书:

Parsing public keys form a X.509 certificate and representing them as a Hex number turned out simple and easy.

openssl x509 -modulus -noout < pub.cer | sed s/Modulus=/0x/

Just replace pub.cer with the certificate file you want to parse

这使用了 modulus option.

结果应该是这样的:

0xB1E057678343....

注意:以上内容适用于 X.509v3 文件,其中包含 ASCII (Base64) 装甲数据,前缀为“—– BEGIN …”行(即实际 PEM 文件)。

如果您收到以下错误,则表示您正在尝试查看 DER 编码证书:

unable to load certificate
PEM routines:PEM_read_bio:no start line:pem_lib.c:
Expecting: TRUSTED CERTIFICATE

对于der文件,还要注意the public key in DER format (which is a way of expressing X.509 objects as a sequence of bytes) includes more than just the modulus, but also the exponent (usually short) and the algorithm identifier

转换 certificate from DER to PEM first:

openssl x509 -inform der -in certificate.cer -out certificate.pem

然后重试