"""Turn a PEM CA bundle into assets/roots/-.der for the app's trust store.""" import hashlib import os import sys from cryptography import x509 from cryptography.hazmat.primitives.serialization import Encoding def main(pem_path, out_dir): os.makedirs(out_dir, exist_ok=True) for f in os.listdir(out_dir): os.remove(os.path.join(out_dir, f)) data = open(pem_path, "rb").read() certs = x509.load_pem_x509_certificates(data) counts = {} for c in certs: h = hashlib.sha1(c.subject.public_bytes()).hexdigest() n = counts.get(h, 0) counts[h] = n + 1 with open(os.path.join(out_dir, "%s-%d.der" % (h, n)), "wb") as fh: fh.write(c.public_bytes(Encoding.DER)) print("wrote %d roots to %s" % (len(certs), out_dir)) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])