#!/usr/bin/env python3
import hashlib
import base64
import sys
from cryptography import x509
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.hazmat.primitives import serialization

pem_data = b''
with open(sys.argv[1], "rb") as file:
    pem_data = file.read()

# read certificate
cert = x509.load_pem_x509_certificate(pem_data)
der = cert.public_key().public_bytes(
		encoding=serialization.Encoding.DER,
		format=serialization.PublicFormat.SubjectPublicKeyInfo
	)
print("DER(1) : %s" % der.hex())

# Delete DER RSAEncryption DER ASN.1 Header (24 bytes)
# rsa2048 ASN1 header is : 
#		0x30, 0x82, 0x01, 0x22, 
#		0x30, 0x0d, 0x06, 0x09, 
#		0x2a, 0x86, 0x48, 0x86, 
#		0xf7, 0x0d, 0x01, 0x01,
#		0x01, 0x05, 0x00, 0x03,
#		0x82, 0x01, 0x0f, 0x00
der = der[24:]
print("DER(2) : %s" % der.hex())
# der contains now pubkey DER ASN.1 format without header

# Create SHA1 fingerprint from pubkey DER ASN.1 format
engine = hashlib.sha1()
engine.update(der)
sha1 = engine.digest()
print("SHA1 : %s" % sha1.hex())

# Wrap on base64
hash = base64.b64encode(sha1)

# That's it ! :)
print("dnQualifier = %s" % hash.decode('utf8'))
