Coverage for jbank/x509_helpers.py: 48%

21 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-27 13:36 +0700

1import logging 

2import cryptography 

3from cryptography import x509 

4from django.core.exceptions import ValidationError 

5 

6logger = logging.getLogger(__name__) 

7 

8 

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

10 """ 

11 Load X509 certificate from file. 

12 """ 

13 with open(filename, "rb") as fp: 

14 pem_data = fp.read() 

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

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.strip() + b"\n") 

32 blocks = blocks[64:] 

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

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