gen_cert_header.py (1480B)
1 # This Source Code Form is subject to the terms of the Mozilla Public 2 # License, v. 2.0. If a copy of the MPL was not distributed with this 3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 5 import textwrap 6 7 from pyasn1_modules import pem 8 9 10 def read_certificate(filename): 11 with open(filename) as f: 12 try: 13 return pem.readPemFromFile( 14 f, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----" 15 ) 16 except UnicodeDecodeError: 17 raise Exception( 18 f"Could not decode {filename} (it should be a PEM-encoded certificate)" 19 ) 20 21 22 def write_header(output, array_name, certificates): 23 certificate_names = [] 24 for index, certificate in enumerate(certificates): 25 certificate_name = f"{array_name}{index}" 26 certificate_names.append( 27 f"mozilla::Span({certificate_name}, sizeof({certificate_name}))" 28 ) 29 output.write(f"const uint8_t {certificate_name}[] = {{\n") 30 certificate_bytes = read_certificate(certificate) 31 hexified = ", ".join(["0x%02x" % byte for byte in certificate_bytes]) 32 wrapped = textwrap.wrap(hexified) 33 for line in wrapped: 34 output.write(f" {line}\n") 35 output.write("};\n") 36 output.write( 37 f"const mozilla::Span<const uint8_t> {array_name}[] = {{ {', '.join(certificate_names)} }};\n" 38 ) 39 40 41 def generate(output, *args): 42 write_header(output, args[-1], args[0:-1])