Skip to content

Instantly share code, notes, and snippets.

@alexanderankin
Last active October 14, 2023 02:14
Show Gist options
  • Save alexanderankin/1f9938277ff8456a011f223126982f5b to your computer and use it in GitHub Desktop.
Save alexanderankin/1f9938277ff8456a011f223126982f5b to your computer and use it in GitHub Desktop.
import hashlib
import pathlib
import subprocess
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.backends import default_backend
# openssl req -new -newkey rsa:2048 -sha256 -nodes -x509 -keyout demo.key -out demo.crt -subj "/CN=foo"
file = pathlib.Path.home() / "demo.crt"
cmd = f"openssl x509 -noout -fingerprint -sha1 -inform pem -in {file} | sed 's/.*=//'"
print(f'expected: {subprocess.getoutput(cmd)}')
print()
def hazmat(cert_file_path):
# Read the X.509 certificate from a file (PEM format)
cert_data = pathlib.Path(cert_file_path).read_bytes()
# Parse the X.509 certificate
pb = load_pem_x509_certificate(cert_data, default_backend()) \
.public_bytes(encoding=Encoding.DER)
return hashlib.sha1(pb).hexdigest()
fingerprint = hazmat(file)
print(f'actual: {fingerprint}')
print(f"alternatively: {':'.join(a + b for a, b in zip(fingerprint[::2], fingerprint[1::2]))}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment