@@ -279,19 +279,35 @@ def __init__(self, entry):
279279 self .__dict__ .update (entry )
280280
281281 if self .certificate :
282- from OpenSSL .crypto import load_certificate , FILETYPE_PEM , Error
282+ from cryptography .x509 import load_pem_x509_certificate
283+ from cryptography .hazmat .primitives import hashes
284+
283285 try :
284- with open (self .certificate , 'r' ) as file_reader :
285- self ._certificate_string = file_reader .read ()
286- cert = load_certificate (FILETYPE_PEM , self ._certificate_string )
287- self ._thumbprint = cert .digest ("sha1" ).decode ().replace (':' , '' )
286+ with open (self .certificate , 'rb' ) as f :
287+ certificate_bytes = f .read ()
288+ self ._certificate_string = certificate_bytes .decode ('utf-8' )
289+
290+ # Calculate SHA1 thumbprint of the PEM certificate.
291+ # The certificate should look like
292+ # -----BEGIN CERTIFICATE-----
293+ # ...
294+ # -----END CERTIFICATE-----
295+
296+ # For invalid certificate, load_pem_x509_certificate will raise:
297+ # ValueError: Unable to load PEM file.
298+ x509_cert = load_pem_x509_certificate (certificate_bytes )
299+
300+ # x509_cert.fingerprint(hashes.SHA1()) generates a thumbprint like
301+ # b'\xd4S\x17\x08...'
302+ self ._thumbprint = x509_cert .fingerprint (hashes .SHA1 ()).hex ().upper ()
303+
288304 if entry .get (_USE_CERT_SN_ISSUER ):
289305 # low-tech but safe parsing based on
290306 # https://github.com/libressl-portable/openbsd/blob/master/src/lib/libcrypto/pem/pem.h
291307 match = re .search (r'-----BEGIN CERTIFICATE-----(?P<cert_value>[^-]+)-----END CERTIFICATE-----' ,
292308 self ._certificate_string , re .I )
293309 self ._public_certificate = match .group ()
294- except (UnicodeDecodeError , Error ) as ex :
310+ except (UnicodeDecodeError , ValueError ) as ex :
295311 raise CLIError ('Invalid certificate, please use a valid PEM file. Error detail: {}' .format (ex ))
296312
297313 @classmethod
0 commit comments