def _certificate_chain_to_xml(certificate_chain: List[Certificate]) -> List[Element]: cert_xml_list = [] for certificate in certificate_chain: cert_xml = Element('certificate', attrib={ 'sha1Fingerprint': binascii.hexlify(certificate.fingerprint(hashes.SHA1())).decode('ascii'), 'hpkpSha256Pin': CertificateUtils.get_hpkp_pin(certificate) }) # Add the PEM cert cert_as_pem_xml = Element('asPEM') cert_as_pem_xml.text = certificate.public_bytes(Encoding.PEM).decode('ascii') cert_xml.append(cert_as_pem_xml) # Add some of the fields of the cert elem_xml = Element('subject') elem_xml.text = CertificateUtils.get_name_as_text(certificate.subject) cert_xml.append(elem_xml) elem_xml = Element('issuer') elem_xml.text = CertificateUtils.get_name_as_text(certificate.issuer) cert_xml.append(elem_xml) elem_xml = Element('serialNumber') elem_xml.text = str(certificate.serial_number) cert_xml.append(elem_xml) elem_xml = Element('notBefore') elem_xml.text = certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S") cert_xml.append(elem_xml) elem_xml = Element('notAfter') elem_xml.text = certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S") cert_xml.append(elem_xml) elem_xml = Element('signatureAlgorithm') elem_xml.text = certificate.signature_hash_algorithm.name cert_xml.append(elem_xml) key_attrs = {'algorithm': CertificateUtils.get_public_key_type(certificate)} public_key = certificate.public_key() key_attrs['size'] = str(public_key.key_size) if isinstance(public_key, EllipticCurvePublicKey): key_attrs['curve'] = public_key.curve.name else: key_attrs['exponent'] = str(public_key.public_numbers().e) elem_xml = Element('publicKey', attrib=key_attrs) cert_xml.append(elem_xml) dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate) if dns_alt_names: san_xml = Element('subjectAlternativeName') for dns_name in dns_alt_names: dns_xml = Element('DNS') dns_xml.text = dns_name san_xml.append(dns_xml) cert_xml.append(san_xml) cert_xml_list.append(cert_xml) return cert_xml_list
def _object_to_json_dict(obj): """Convert an object to a dictionary suitable for the JSON output. """ if isinstance(obj, Enum): # Properly serialize Enums (such as OpenSslVersionEnum) result = obj.name elif isinstance(obj, x509._Certificate): # Properly serialize certificates certificate = obj result = { # Add general info 'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'), 'hpkp_pin': CertificateUtils.get_hpkp_pin(obj), # Add some of the fields of the cert 'subject': CertificateUtils.get_name_as_text(certificate.subject), 'issuer': CertificateUtils.get_name_as_text(certificate.issuer), 'serialNumber': str(certificate.serial_number), 'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"), 'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"), 'signatureAlgorithm': certificate.signature_hash_algorithm.name, 'publicKey': { 'algorithm': CertificateUtils.get_public_key_type(certificate) }, } dns_alt_names = CertificateUtils.get_dns_subject_alternative_names( certificate) if dns_alt_names: result['subjectAlternativeName'] = {'DNS': dns_alt_names} # Add some info about the public key public_key = certificate.public_key() if isinstance(public_key, EllipticCurvePublicKey): result['publicKey']['size'] = str(public_key.curve.key_size) result['publicKey']['curve'] = public_key.curve.name else: result['publicKey']['size'] = str(public_key.key_size) result['publicKey']['exponent'] = str( public_key.public_numbers().e) elif isinstance(obj, object): if hasattr(obj, '__dict__'): result = {} for key, value in obj.__dict__.items(): # Remove private attributes if key.startswith('_'): continue result[key] = _object_to_json_dict(value) else: # Simple object like a string result = obj else: raise TypeError('Unknown type: {}'.format(repr(obj))) return result
def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]: """Convert an object to a dictionary suitable for the JSON output. """ if isinstance(obj, Enum): # Properly serialize Enums (such as OpenSslVersionEnum) result = obj.name elif isinstance(obj, x509._Certificate): # Properly serialize certificates certificate = obj result = { # type: ignore # Add general info 'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'), 'hpkp_pin': CertificateUtils.get_hpkp_pin(obj), # Add some of the fields of the cert 'subject': CertificateUtils.get_name_as_text(certificate.subject), 'issuer': CertificateUtils.get_name_as_text(certificate.issuer), 'serialNumber': str(certificate.serial_number), 'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"), 'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"), 'signatureAlgorithm': certificate.signature_hash_algorithm.name, 'publicKey': { 'algorithm': CertificateUtils.get_public_key_type(certificate) }, } dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate) if dns_alt_names: result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore # Add some info about the public key public_key = certificate.public_key() if isinstance(public_key, EllipticCurvePublicKey): result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore result['publicKey']['curve'] = public_key.curve.name # type: ignore else: result['publicKey']['size'] = str(public_key.key_size) result['publicKey']['exponent'] = str(public_key.public_numbers().e) elif isinstance(obj, object): # Some objects (like str) don't have a __dict__ if hasattr(obj, '__dict__'): result = {} for key, value in obj.__dict__.items(): # Remove private attributes if key.startswith('_'): continue result[key] = _object_to_json_dict(value) else: # Simple object like a bool result = obj else: raise TypeError('Unknown type: {}'.format(repr(obj))) return result
def default(self, obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]: result: Union[bool, int, float, str, Dict[str, Any]] if isinstance(obj, Enum): result = obj.name elif isinstance(obj, ObjectIdentifier): result = obj.dotted_string elif isinstance(obj, x509._Certificate): certificate = obj result = { # Add general info "as_pem": obj.public_bytes(Encoding.PEM).decode("ascii"), "hpkp_pin": CertificateUtils.get_hpkp_pin(obj), # Add some of the fields of the cert "subject": CertificateUtils.get_name_as_text(certificate.subject), "issuer": CertificateUtils.get_name_as_text(certificate.issuer), "serialNumber": str(certificate.serial_number), "notBefore": certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"), "notAfter": certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"), "signatureAlgorithm": certificate.signature_hash_algorithm.name, "publicKey": { "algorithm": CertificateUtils.get_public_key_type(certificate) }, } dns_alt_names = CertificateUtils.get_dns_subject_alternative_names( certificate) if dns_alt_names: result["subjectAlternativeName"] = { "DNS": dns_alt_names } # type: ignore # Add some info about the public key public_key = certificate.public_key() if isinstance(public_key, EllipticCurvePublicKey): result["publicKey"]["size"] = str( public_key.curve.key_size) # type: ignore result["publicKey"][ "curve"] = public_key.curve.name # type: ignore else: result["publicKey"]["size"] = str(public_key.key_size) result["publicKey"]["exponent"] = str( public_key.public_numbers().e) elif isinstance(obj, Path): result = str(obj) elif isinstance(obj, object): # Some objects (like str) don't have a __dict__ if hasattr(obj, "__dict__"): result = {} for key, value in obj.__dict__.items(): # Remove private attributes if key.startswith("_"): continue result[key] = self.default(value) else: # Simple object like a bool result = obj # type: ignore else: raise TypeError("Unknown type: {}".format(repr(obj))) return result