jwcrypto: JOSE Web Standards Implementation

1.5.6 · active · verified Sun Apr 05

JWCrypto is a Python library that implements the Javascript Object Signing and Encryption (JOSE) Web Standards, including JSON Web Key (JWK), JSON Web Signature (JWS), JSON Web Encryption (JWE), and JSON Web Token (JWT). It leverages the `cryptography` package for its underlying cryptographic functions, ensuring strong security. The library is actively maintained, with frequent releases addressing security vulnerabilities and compatibility, currently at version 1.5.6.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a symmetric key, sign a payload using JWS, and then verify the signed token. It utilizes `jwk` for key management and `jws` for signature operations, along with `jwcrypto.common` for JSON encoding.

from jwcrypto import jwk, jws
from jwcrypto.common import json_encode

# 1. Generate a symmetric key
key = jwk.JWK.generate(kty='oct', size=256)

# 2. Define the payload and JWS headers
payload = "My Integrity protected message"
jwstoken = jws.JWS(payload.encode('utf-8'))

# 3. Add signature to the token
jwstoken.add_signature(
    key,
    None,
    json_encode({"alg": "HS256"}),
    json_encode({"kid": key.thumbprint()})
)

# 4. Serialize the JWS token
signed_token = jwstoken.serialize()
print(f"Signed JWS: {signed_token}")

# 5. Verify the JWS token
verifier_token = jws.JWS()
verifier_token.deserialize(signed_token)
verifier_token.verify(key)

# 6. Access the verified payload
verified_payload = verifier_token.payload.decode('utf-8')
print(f"Verified Payload: {verified_payload}")

view raw JSON →