From 71e316da896f05b703f365a077550e5919ea5a38 2018-03-01 13:27:23 From: Branko Majic Date: 2018-03-01 13:27:23 Subject: [PATCH] GC-3: Implemented storage function for writing certificate chain to a file. --- diff --git a/gimmecert/storage.py b/gimmecert/storage.py index 38972481926efae6775583249cd5027d17e6af1b..c966c9227a69eca65f961c50912d2b1d027fb11b 100644 --- a/gimmecert/storage.py +++ b/gimmecert/storage.py @@ -23,6 +23,8 @@ import os import cryptography.hazmat.primitives.serialization +import gimmecert.utils + def initialise_storage(project_directory): """ @@ -83,3 +85,24 @@ def write_certificate(certificate, path): with open(path, 'wb') as certificate_file: certificate_file.write(certificate_pem) + + +def write_certificate_chain(certificate_chain, path): + """ + Writes the passed-in certificate chain to designated path in + OpenSSL-style PEM format. Certificates are separated with + newlines. + + :param certificate_chain: List of certificates to output to the file. + :type certificate_chain: list[cryptography.x509.Certificate] + + :param path: File path where the chain should be written. + :type path: str + """ + + chain_pem = b"\n".join( + [gimmecert.utils.certificate_to_pem(certificate) for certificate in certificate_chain] + ) + + with open(path, 'wb') as certificate_chain_file: + certificate_chain_file.write(chain_pem) diff --git a/tests/test_storage.py b/tests/test_storage.py index 5dbec4574333a8b157d168fc978af7d7b972d80e..646d7cd8bb960b6a345a76fd352cd59f49788566 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -22,6 +22,7 @@ import os import gimmecert.crypto import gimmecert.storage +import gimmecert.utils def test_initialise_storage(tmpdir): @@ -69,3 +70,15 @@ def test_write_certificate(tmpdir): content = certificate_file.read() assert 'BEGIN CERTIFICATE' in content assert 'END CERTIFICATE' in content + + +def test_write_certificate_chain(tmpdir): + output_file = tmpdir.join('chain.cert.pem') + certificate_chain = [certificate for _, certificate in gimmecert.crypto.generate_ca_hierarchy('My Project', 3)] + level1_pem, level2_pem, level3_pem = [gimmecert.utils.certificate_to_pem(certificate) for certificate in certificate_chain] + + gimmecert.storage.write_certificate_chain(certificate_chain, output_file.strpath) + content = output_file.read(mode='rb') + expected_content = b"%s\n%s\n%s" % (level1_pem, level2_pem, level3_pem) + + assert content == expected_content