Skip to content

Instantly share code, notes, and snippets.

@Te-k
Created November 23, 2017 23:12
Show Gist options
  • Save Te-k/b93a4447f3d0b4f6c7fcf8d4542fae96 to your computer and use it in GitHub Desktop.
Save Te-k/b93a4447f3d0b4f6c7fcf8d4542fae96 to your computer and use it in GitHub Desktop.
Parse a certificates and print data as csv
import argparse
import OpenSSL
from dateutil.parser import parse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process some certs')
parser.add_argument('CERT', help="Cert file to parse")
args = parser.parse_args()
with open(args.CERT, 'r') as f:
data = f.read()
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, data)
subject = dict(cert.get_subject().get_components())
issuer = dict(cert.get_issuer().get_components())
not_before = parse(cert.get_notBefore().decode('utf-8'))
not_after = parse(cert.get_notAfter().decode('utf-8'))
serial = cert.get_serial_number()
sha1 = cert.digest("sha1").decode('utf-8').replace(":", "")
basic_constraints = False
alt_names = []
for c in range(cert.get_extension_count()):
ext = cert.get_extension(c)
if ext.get_short_name() == b'basicConstraints':
if ext.get_data() == b'0\x00':
basic_constraints = False
else:
basic_constraints = True
if ext.get_short_name() == b'subjectAltName':
dat = ext.get_data()
# Ugly ASN1 decoder
i = 3
while i < len(dat):
alt_names.append(dat[i+1:dat[i]+i+1].decode('utf-8'))
i += dat[i] + 2
print("%s|%s|%s|%s|%s|%s|%s|%s|%s" % (
"", # id
hex(serial)[2:], # serial
sha1, #sha1
subject[b'CN'].decode('utf-8'), # Common Name
issuer[b'CN'].decode('utf-8'), #Issuer
not_before.isoformat(), # Not Before
not_after.isoformat(), # Not After
str(basic_constraints), # Basic Constraints
", ".join(alt_names) # Alt names
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment