Last active
April 14, 2020 18:13
-
-
Save Bouni/1debc145a53bc5c98b8aec60598a7d55 to your computer and use it in GitHub Desktop.
Extract pem files from traefiks acme.json
This file contains hidden or 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
import sys | |
import os | |
import errno | |
import json | |
from base64 import b64decode | |
def extract(file, output, challenge): | |
# Read JSON file | |
data = json.loads(open(file).read()) | |
certs = data[challenge]['Certificates'] | |
print('Certificate storage contains ' + str(len(certs)) + ' certificates') | |
# Loop over all certificates | |
for c in certs: | |
name = c['domain']['main'] | |
privatekey = c['key'] | |
fullchain = c['certificate'] | |
# Decode private key, certificate and chain | |
privatekey = b64decode(privatekey).decode('utf-8') | |
fullchain = b64decode(fullchain).decode('utf-8') | |
start = fullchain.find('-----BEGIN CERTIFICATE-----', 1) | |
cert = fullchain[0:start] | |
chain = fullchain[start:] | |
# Create domain directory if it doesn't exist | |
directory = output + '/' + name + '/' | |
try: | |
os.makedirs(directory) | |
except OSError as error: | |
if error.errno != errno.EEXIST: | |
raise | |
# Write private key, certificate and chain to file | |
with open(directory + 'privkey.pem', 'w') as f: | |
f.write(privatekey) | |
with open(directory + 'cert.pem', 'w') as f: | |
f.write(cert) | |
with open(directory + 'chain.pem', 'w') as f: | |
f.write(chain) | |
with open(directory + 'fullchain.pem', 'w') as f: | |
f.write(fullchain) | |
if __name__ == "__main__": | |
extract(sys.argv[1], sys.argv[2], sys.argv[3]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment