Skip to content

Instantly share code, notes, and snippets.

@skion
Created June 21, 2016 10:17

Revisions

  1. skion created this gist Jun 21, 2016.
    38 changes: 38 additions & 0 deletions pem_to_jwk.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    Convert a PEM encoded X509 certificate into a JWK RSA public key.
    """
    import base64
    import json

    from cryptography import x509
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend

    file_name = "instance/cert.pem"

    pem_data = open(file_name, "rb").read()
    cert = x509.load_pem_x509_certificate(pem_data, default_backend())

    public_key = cert.public_key()
    public_numbers = public_key.public_numbers()

    e = public_numbers.e.to_bytes(3, byteorder="big")
    n = public_numbers.n.to_bytes(256, byteorder="big")
    x5c = cert.public_bytes(serialization.Encoding.DER)

    e = base64.urlsafe_b64encode(e).rstrip(b"=").decode("ascii")
    n = base64.urlsafe_b64encode(n).rstrip(b"=").decode("ascii")
    x5c = base64.b64encode(x5c).decode("ascii")

    jwk = {
    "kty": "RSA",
    "use": "sig",
    "alg": "RS256",
    "e": e,
    "n": n,
    "x5c": x5c,
    }

    print(json.dumps(jwk, indent=4))