Skip to content

Instantly share code, notes, and snippets.

@NCommander
Last active January 7, 2022 06:32
Show Gist options
  • Save NCommander/6111c08a5d6be85d483727b15803b0c7 to your computer and use it in GitHub Desktop.
Save NCommander/6111c08a5d6be85d483727b15803b0c7 to your computer and use it in GitHub Desktop.
Implement RFC 7638 with python-jose
#!/usr/bin/env python3
"""Quick and dirty python-jose kid generator
This is needed because jose doesn't offer a way to generate the key
thumbprint in a RFC 7638 complaint matter, and it's the only library
that can handle both EC signatures, and is MIT license compatible
"""
import base64
import json
import hashlib
from cryptography import x509
from jose import jwk, jws
from jose.constants import ALGORITHMS
def generate_kid(jwks_dict):
"""Generates KID token per RFC 7638"""
kid_base = {}
kid_base['crv'] = jwks_dict['crv']
kid_base['kty'] = jwks_dict['kty']
kid_base['x'] = jwks_dict['x']
kid_base['y'] = jwks_dict['y']
#kid_base["e"] = "AQAB"
#kid_base["kty"] = "RSA"
#kid_base["n"] = "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"
json_serial = json.dumps(kid_base, sort_keys=True, separators=(',', ':'))
sha256_hash = hashlib.sha256(json_serial.encode('utf-8')).digest()
b64_hash = base64.urlsafe_b64encode(sha256_hash)
return b64_hash.decode('utf-8').rstrip("=")
def main():
with open("jwks.json", "r") as f:
keys = json.loads(f.read())
print(keys['keys'][0]['kid'])
public_key = jwk.construct(keys['keys'][0], algorithm=ALGORITHMS.ES256)
print(generate_kid(public_key.to_dict()))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment