Changeset - 71e316da896f
[Not reviewed]
0 2 0
Branko Majic (branko) - 7 years ago 2018-03-01 13:27:23
branko@majic.rs
GC-3: Implemented storage function for writing certificate chain to a file.
2 files changed with 36 insertions and 0 deletions:
0 comments (0 inline, 0 general)
gimmecert/storage.py
Show inline comments
 
@@ -20,12 +20,14 @@
 

	
 

	
 
import os
 

	
 
import cryptography.hazmat.primitives.serialization
 

	
 
import gimmecert.utils
 

	
 

	
 
def initialise_storage(project_directory):
 
    """
 
    Initialises certificate storage in the given project directory.
 

	
 
    Storage initialisation consists of creating the necessary
 
@@ -80,6 +82,27 @@ def write_certificate(certificate, path):
 
    """
 

	
 
    certificate_pem = certificate.public_bytes(encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM)
 

	
 
    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)
tests/test_storage.py
Show inline comments
 
@@ -19,12 +19,13 @@
 
#
 

	
 
import os
 

	
 
import gimmecert.crypto
 
import gimmecert.storage
 
import gimmecert.utils
 

	
 

	
 
def test_initialise_storage(tmpdir):
 
    tmpdir.chdir()
 

	
 
    gimmecert.storage.initialise_storage(tmpdir.strpath)
 
@@ -66,6 +67,18 @@ def test_write_certificate(tmpdir):
 
    assert os.path.exists(certificate_path)
 

	
 
    with open(certificate_path, 'r') as certificate_file:
 
        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
0 comments (0 inline, 0 general)