|
| 1 | +import binascii |
| 2 | +import hashlib |
| 3 | +import hmac |
| 4 | +import json |
| 5 | +from time import time |
| 6 | + |
| 7 | + |
| 8 | +def _to_b64url(data): |
| 9 | + return ( |
| 10 | + binascii.b2a_base64(data) |
| 11 | + .rstrip(b"\n") |
| 12 | + .rstrip(b"=") |
| 13 | + .replace(b"+", b"-") |
| 14 | + .replace(b"/", b"_") |
| 15 | + ) |
| 16 | + |
| 17 | + |
| 18 | +def _from_b64url(data): |
| 19 | + return binascii.a2b_base64(data.replace(b"-", b"+").replace(b"_", b"/") + b"===") |
| 20 | + |
| 21 | + |
| 22 | +class exceptions: |
| 23 | + class PyJWTError(Exception): |
| 24 | + pass |
| 25 | + |
| 26 | + class InvalidTokenError(PyJWTError): |
| 27 | + pass |
| 28 | + |
| 29 | + class InvalidAlgorithmError(PyJWTError): |
| 30 | + pass |
| 31 | + |
| 32 | + class InvalidSignatureError(PyJWTError): |
| 33 | + pass |
| 34 | + |
| 35 | + class ExpiredTokenError(PyJWTError): |
| 36 | + pass |
| 37 | + |
| 38 | + |
| 39 | +def encode(payload, key, algorithm="HS256"): |
| 40 | + if algorithm != "HS256": |
| 41 | + raise exceptions.InvalidAlgorithmError() |
| 42 | + |
| 43 | + if isinstance(key, str): |
| 44 | + key = key.encode() |
| 45 | + header = _to_b64url(json.dumps({"typ": "JWT", "alg": algorithm}).encode()) |
| 46 | + payload = _to_b64url(json.dumps(payload).encode()) |
| 47 | + signature = _to_b64url(hmac.new(key, header + b"." + payload, hashlib.sha256).digest()) |
| 48 | + return (header + b"." + payload + b"." + signature).decode() |
| 49 | + |
| 50 | + |
| 51 | +def decode(token, key, algorithms=["HS256"]): |
| 52 | + if "HS256" not in algorithms: |
| 53 | + raise exceptions.InvalidAlgorithmError() |
| 54 | + |
| 55 | + parts = token.encode().split(b".") |
| 56 | + if len(parts) != 3: |
| 57 | + raise exceptions.InvalidTokenError() |
| 58 | + |
| 59 | + header = json.loads(_from_b64url(parts[0]).decode()) |
| 60 | + payload = json.loads(_from_b64url(parts[1]).decode()) |
| 61 | + signature = _from_b64url(parts[2]) |
| 62 | + |
| 63 | + if header["alg"] not in algorithms or header["alg"] != "HS256": |
| 64 | + raise exceptions.InvalidAlgorithmError() |
| 65 | + |
| 66 | + if isinstance(key, str): |
| 67 | + key = key.encode() |
| 68 | + calculated_signature = hmac.new(key, parts[0] + b"." + parts[1], hashlib.sha256).digest() |
| 69 | + if signature != calculated_signature: |
| 70 | + raise exceptions.InvalidSignatureError() |
| 71 | + |
| 72 | + if "exp" in payload: |
| 73 | + if time() > payload["exp"]: |
| 74 | + raise exceptions.ExpiredTokenError() |
| 75 | + |
| 76 | + return payload |
0 commit comments