Last active
March 16, 2024 02:11
-
-
Save mrhockeymonkey/bdf6a9fcffd6d6a423118103e2322a27 to your computer and use it in GitHub Desktop.
Verify certificates with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from base64 import b64decode | |
from OpenSSL import crypto | |
def verify_chain_of_trust(certificate, trusted_cert_pems): | |
# Create and fill a X509Sore with trusted certs | |
store = crypto.X509Store() | |
for trusted_cert_pem in trusted_cert_pems: | |
trusted_cert = crypto.load_certificate(crypto.FILETYPE_PEM, trusted_cert_pem) | |
store.add_cert(trusted_cert) | |
# Create a X590StoreContext with the cert and trusted certs | |
# and verify the the chain of trust | |
store_ctx = crypto.X509StoreContext(store, certificate) | |
# Returns None if certificate can be validated | |
result = store_ctx.verify_certificate() | |
if result is None: | |
return True | |
else: | |
return False | |
if __name__ == "__main__": | |
# get certificate bytes from base64, could also be be done with file | |
cert_base64 = 'MIIGlTCCBX2gAwIBA...KjLmgBg+zE8' | |
cert_bytes = b64decode(cert_base64) | |
# cert_bytes = open("certificate.cer", "rb").read() | |
cert = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_bytes) # ASN1 is for der encoded certs | |
thumbprint = cert.digest("SHA1").decode("utf-8") | |
print(thumbprint) | |
trusted_cert_pems = [] | |
trusted_cert_pems.append(open("root.crt", "rb").read()) | |
trusted_cert_pems.append(open("issuing.crt", "rb").read()) | |
trusted = verify_chain_of_trust(cert, trusted_cert_pems) | |
print(trusted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment