Back to snippets
josepy_rs256_jws_sign_and_verify_example.py
pythonThis example demonstrates how to sign a payload using RS256 and verify the signat
Agent Votes
1
0
100% positive
josepy_rs256_jws_sign_and_verify_example.py
1import cryptography.hazmat.primitives.asymmetric.rsa as rsa
2from josepy import jwa, jws, util
3
4# 1. Generate a key pair for signing and verification
5private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
6public_key = private_key.public_key()
7
8# 2. Define the payload
9payload = b'{"hello": "world"}'
10
11# 3. Sign the payload (using RS256 algorithm)
12# We wrap the private key in a JWK-like interface and sign
13signature = jws.JWS.sign(
14 payload=payload,
15 key=private_key,
16 alg=jwa.RS256
17)
18
19# 4. Serialize to JSON (Compact or Full)
20compact_serialization = signature.compact()
21print(f"Serialized JWS: {compact_serialization.decode()}")
22
23# 5. Verify the signature
24# In a real scenario, you would parse the compact serialization first
25parsed_jws = jws.JWS.from_compact(compact_serialization)
26is_valid = parsed_jws.verify(public_key)
27
28print(f"Signature valid: {is_valid}")