Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import logging 

2import cryptography 

3from cryptography import x509 

4from django.core.exceptions import ValidationError 

5 

6 

7logger = logging.getLogger(__name__) 

8 

9 

10def get_x509_cert_from_file(filename: str) -> x509.Certificate: 

11 """ 

12 Load X509 certificate from file. 

13 """ 

14 pem_data = open(filename, 'rb').read() 

15 return x509.load_pem_x509_certificate(pem_data, cryptography.hazmat.backends.default_backend()) 

16 

17 

18def write_cert_pem_file(filename: str, cert_base64: bytes): 

19 """ 

20 Writes PEM data to file. 

21 :param filename: PEM filename 

22 :param cert_base64: Base64 encoded certificate data without BEGIN CERTIFICATE / END CERTIFICATE 

23 """ 

24 if b'BEGIN' in cert_base64 or b'END' in cert_base64: 

25 raise ValidationError('write_cert_pem_file() assumes PEM data does not contain header/footer') 

26 with open(filename, 'wb') as fp: 

27 fp.write(b'-----BEGIN CERTIFICATE-----\n') 

28 blocks = cert_base64 

29 while blocks: 

30 block = blocks[:64] 

31 fp.write(block + b'\n') 

32 blocks = blocks[64:] 

33 fp.write(b'-----END CERTIFICATE-----\n') 

34 logger.info('%s written', filename)