Created
February 17, 2017 09:47
-
-
Save Lukasa/0cd4d349acc711ce9bdb3d10ed6779a6 to your computer and use it in GitHub Desktop.
Copy a certificate using cryptography
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
A script that takes a path to a given cert and key and rebuilds them in new | |
files. | |
""" | |
import sys | |
from cryptography import x509 | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives import hashes, serialization | |
def build_matching_cert(cert, private_key): | |
builder = x509.CertificateBuilder() | |
builder = builder.subject_name(cert.subject) | |
builder = builder.issuer_name(cert.issuer) | |
builder = builder.not_valid_before(cert.not_valid_before) | |
builder = builder.not_valid_after(cert.not_valid_after) | |
builder = builder.serial_number(cert.serial_number) | |
builder = builder.public_key(cert.public_key()) | |
# Copy over all the extensions | |
for extension in cert.extensions: | |
builder = builder.add_extension(extension.value, extension.critical) | |
# Now we need to sign the cert. We want to use the same algorithm as | |
# before. | |
new_cert = builder.sign( | |
private_key=private_key, | |
algorithm=cert.signature_hash_algorithm, | |
backend=default_backend() | |
) | |
return new_cert | |
def main(): | |
cert_name = sys.argv[1] | |
key_name = sys.argv[2] | |
with open(cert_name, 'rb') as f: | |
cert = x509.load_pem_x509_certificate(f.read(), default_backend()) | |
with open(key_name, 'rb') as f: | |
key = serialization.load_pem_private_key( | |
f.read(), None, default_backend() | |
) | |
# Ok, so we want to create a new cert from the old one. We use a | |
# cert_builder for this. | |
new_cert = build_matching_cert(cert, key) | |
with open(cert_name + '.new', 'wb') as f: | |
f.write(new_cert.public_bytes(serialization.Encoding.PEM)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment