Skip to content

Instantly share code, notes, and snippets.

@Bouni
Last active April 14, 2020 18:13
Show Gist options
  • Save Bouni/1debc145a53bc5c98b8aec60598a7d55 to your computer and use it in GitHub Desktop.
Save Bouni/1debc145a53bc5c98b8aec60598a7d55 to your computer and use it in GitHub Desktop.
Extract pem files from traefiks acme.json
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