Skip to content

Instantly share code, notes, and snippets.

@zengxs
Created July 2, 2017 00:50
Show Gist options
  • Save zengxs/564d6469543980ea24763418c312156a to your computer and use it in GitHub Desktop.
Save zengxs/564d6469543980ea24763418c312156a to your computer and use it in GitHub Desktop.
Convert JWK(JSON Web Key) to Private Key(PEM)
#!/usr/bin/env python3
#
# pip install cryptography, pyjwt
from jwt.utils import (
base64url_decode,
bytes_to_number,
)
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
jwk = {
"kty": "EC",
"crv": "P-384",
"x": "Y554xTwvkMJRVpnYomIAG92Zz3abhcO9iXOr3GRCQFMT69J51tShRWF25VfRjn-i",
"y": "l84NkNv5BYHZx6zj7Jdp2KldqAq5cfU7PkwZuawR-LJ7TNAoiq8jtMRmBbh70Ibp",
"d": "0FWZxB4ChgU2lAmFNUvbLk_sGXtf37HQnxKp3p85eIyatCbcQpEbtyUqx9wamuT_"
}
pub_number = ec.EllipticCurvePublicNumbers(
x=bytes_to_number(base64url_decode(jwk['x'])),
y=bytes_to_number(base64url_decode(jwk['y'])),
curve=ec.SECP384R1(),
)
priv_key = ec.EllipticCurvePrivateNumbers(
bytes_to_number(base64url_decode(jwk['d'])),
pub_number).private_key(default_backend())
print(priv_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
).decode('ascii'))
# -----BEGIN PRIVATE KEY-----
# MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDQVZnEHgKGBTaUCYU1
# S9suT+wZe1/fsdCfEqnenzl4jJq0JtxCkRu3JSrH3Bqa5P+hZANiAARjnnjFPC+Q
# wlFWmdiiYgAb3ZnPdpuFw72Jc6vcZEJAUxPr0nnW1KFFYXblV9GOf6KXzg2Q2/kF
# gdnHrOPsl2nYqV2oCrlx9Ts+TBm5rBH4sntM0CiKryO0xGYFuHvQhuk=
# -----END PRIVATE KEY-----
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment