Skip to content

Instantly share code, notes, and snippets.

@ivanov17
Forked from meeuw/rsapem2json.py
Last active August 8, 2021 12:35
Show Gist options
  • Save ivanov17/706f37882ced99c0e48e48529fe3823b to your computer and use it in GitHub Desktop.
Save ivanov17/706f37882ced99c0e48e48529fe3823b to your computer and use it in GitHub Desktop.
Will convert the RSA PEM private key to the Letsencrypt/Certbot private_key.json file. From: https://www.osso.nl/blog/convert-dehydrated-certbot-letsencrypt-config/
#!/usr/bin/env python3
# Usage: openssl rsa -in account_key.pem -text -noout | python3 rsapem2json.py
# Will convert the RSA PEM private key to the Letsencrypt/Certbot
# private_key.json file.
#
# From:
# -----BEGIN RSA PRIVATE KEY-----
# MIIJJwsdAyjCseEAtNsljpkjhk9143w//jVdsfWsdf9sffLgdsf+sefdfsgE54km
# ...
#
# To:
# {"e": "AQAB",
# "n": "2YIitsUxJlYn_rVn_8Sges...",
# ...
#
# Public Domain, Walter Doekes, OSSO B.V., 2016
# Updated to Python 3.6 by Anton Ivanov, Agorist International Conspiracy, 2020
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
#
from base64 import urlsafe_b64encode
from sys import stdin
def block2b64(lines, key):
found = False
chars = list()
for line in lines:
if line.startswith(key + ':'):
found = True
elif found and line.startswith(' '):
chars.append(line.strip())
elif found:
break
assert chars, 'nothing found for {0}'.format(key)
chars = bytearray.fromhex(''.join(chars).replace(':',''))
if chars[0] == 0:
del chars[0]
return urlsafe_b64encode(chars).decode().rstrip('=')
data = stdin.read().splitlines()
maps = {
'modulus': 'n', 'privateExponent': 'd', 'prime1': 'p', 'prime2': 'q',
'exponent1': 'dp', 'exponent2': 'dq', 'coefficient': 'qi'}
conv = dict((v, block2b64(data, k)) for k, v in tuple(maps.items()))
# Add exponent and key type
e = [i for i in data if i.startswith('publicExponent:')][0]
e = e.split('(', 1)[-1].split(')', 1)[0]
assert e.startswith('0x'), e
e = ('', '0')[len(e) % 2 == 1] + e[2:]
e = urlsafe_b64encode(bytes.fromhex(e)).decode()
conv.update({'e': e, 'kty': 'RSA'})
# JSON-safe output.
print((str(conv).replace("'", '"')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment