Skip to content

Instantly share code, notes, and snippets.

@jcjones

jcjones/crtshToDNStruct.py

Last active Oct 19, 2017
Embed
What would you like to do?
Take a list of https://crt.sh/ IDs and produce binary forms of the Subject DNs
import sys, re, requests
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.x509.oid import NameOID
def hex_string_for_struct(bytes):
return [ "0x{:02X}".format(x) for x in bytes ]
def hex_string_human_readable(bytes):
return [ "{:02X}".format(x) for x in bytes ]
def print_block(cert):
country = cert.subject.get_attributes_for_oid(NameOID.COUNTRY_NAME)[0].value
organization_name = cert.subject.get_attributes_for_oid(NameOID.ORGANIZATION_NAME)[0].value
common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value
block_name = "CA{}DN".format(re.sub(r'[-:=_. ]', '', common_name))
octets = hex_string_for_struct(cert.subject.public_bytes(default_backend()))
fingerprint = hex_string_human_readable(cert.fingerprint(hashes.SHA256()))
print("// /C={C}/O={O}/CN={CN}"
.format(C=country, O=organization_name, CN=common_name))
print("// SHA256 Fingerprint: " + ":".join(fingerprint[:16]))
print("// " + ":".join(fingerprint[16:]))
print("// https://crt.sh/?id={crtsh} (crt.sh ID={crtsh})"
.format(crtsh=crtshId))
print("static const uint8_t {}[{}] = ".format(block_name, len(octets)) + "{")
while len(octets) > 0:
print(" " + ", ".join(octets[:13]) + ",")
octets = octets[13:]
print("};")
print()
return block_name
if __name__ == "__main__":
blocks = []
certshIds = sys.argv[1:]
print("// Script downloaded from https://gist.github.com/ed5d869cd8da3951e393f4a2d8a3391f")
print("// Invocation: {} {}".format(sys.argv[0], " ".join(certshIds)))
print()
for crtshId in certshIds:
r = requests.get('https://crt.sh/?d={}'.format(crtshId))
r.raise_for_status()
cert = x509.load_pem_x509_certificate(r.content, default_backend())
blocks.append(print_block(cert))
print("static const DataAndLength RootDNs[]= {")
for structName in blocks:
print(" { " + "{},".format(structName))
print(" sizeof({})".format(structName) + " }")
print("};")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment