Skip to content

Instantly share code, notes, and snippets.

@skion
Created June 21, 2016 10:17
Show Gist options
  • Save skion/e58304855a5fd97ece65e4860e8c0c72 to your computer and use it in GitHub Desktop.
Save skion/e58304855a5fd97ece65e4860e8c0c72 to your computer and use it in GitHub Desktop.
#!/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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment