import base64, json, time, uuid
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization
def b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def public_key(key: Ed25519PrivateKey) -> str:
raw = key.public_key().public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
)
return b64(raw)
def token(key: Ed25519PrivateKey) -> str:
now = int(time.time())
header = {"alg": "EdDSA", "typ": "JWT", "kid": public_key(key)}
claims = {"aud": "https://kovrex.ai", "iat": now, "exp": now + 300, "jti": str(uuid.uuid4())}
signed = b64(json.dumps(header).encode()) + "." + b64(json.dumps(claims).encode())
return signed + "." + b64(key.sign(signed.encode()))
# Once: make the key and store the private half somewhere safe.
key = Ed25519PrivateKey.generate()
print("public key:", public_key(key))
# Every signed call: a fresh token.
headers = {"Authorization": "Bearer " + token(key)}