我正在尝试使用从 openssl 命令获得的 pycryptodome 为 X509 证书生成相同的 SHA1 指纹:
openssl x509 -noout -fingerprint -sha1 -inform pem -in certificate.crt
我的证书在磁盘上是 PEM 格式
但是,下面的代码片段给了我一个不同的值。
from Crypto.PublicKey import RSA
import hashlib
contents = open("/home/ubuntu/certificate.crt", "r").read().encode()
certificate = RSA.import_key(contents)
bytes = certificate.export_key("DER")
hashlib.sha1(bytes).hexdigest()
有人知道我做错了什么吗?
仍然不知道如何使用 Pycryptodome 来完成它,但我发现根本不需要它。以下代码片段生成与 openssl 相同的指纹
pem = open("/home/ubuntu/certificate.crt", "r").read().encode()
pem = pem.removeprefix("-----BEGIN CERTIFICATE-----\n")
pem = pem.removesuffix("-----END CERTIFICATE-----\n")
public_bytes = base64.b64decode(pem)
sha1digest = hashlib.sha1(public_bytes).hexdigest()
fingerprint = ":".join(sha1digest[i : i + 2] for i in range(0, len(sha1digest), 2))
代码仅使用 PyCryptodome 来打印 X.509 证书的指纹:
from Crypto.Hash import SHA1
from Crypto.IO import PEM
filename = "cert.pem"
pem_data = open(filename, "r").read()
der = PEM.decode(pem_data)
h = SHA1.new()
h.update(der[0])
fingerprint = h.hexdigest()
print(fingerprint)
文档:
Crypto.IO.PEM.decode(pem_data,密码=无)
以下示例实现了证书的基本错误检查,并将十六进制字符串添加到 40 个字符,以便它是有效的
kid
:
"""
This code reads an X.509 certificate and prints the SHA-1 fingerprint in hex
"""
import sys
import re
from Crypto.Hash import SHA1
from Crypto.IO import PEM
def get_fingerprint(fname):
"""
Read an X.509 certificate and return the SHA-1 fingerprint in hex
"""
with open(fname, "r", encoding="utf-8") as f:
pem_data = f.read()
r = re.compile(r"\s*-----BEGIN (.*)-----\s+")
m = r.match(pem_data)
marker = m.group(1)
if marker != "CERTIFICATE":
print("Error: Expected X.509 Certificate")
sys.exit(1)
der = PEM.decode(pem_data)
h = SHA1.new()
h.update(der[0])
fingerprint = h.hexdigest()
# insert leading zero bytes to make the string 40 digits
while len(fingerprint) < 40:
fingerprint = '0' + fingerprint
return fingerprint
if __name__ == '__main__':
filename = "cert1.pem"
print(get_fingerprint(filename))