python-jose

repository·master·Indexed 23 days ago

https://github.com/mpdavis/python-jose

A Python implementation of JSON Object Signing and Encryption (JOSE) technologies, including JWS, JWE, JWK, and JWA. It provides modules for encoding and decoding JWTs, signing and verifying JWS tokens, and encrypting and decrypting JWE payloads. The library supports multiple cryptographic backends, including cryptography (recommended), pycryptodome, and native-python.

Tokens
2.6K
Snippets
10
Records
13
Agent score
82%

What's inside python-jose

  1. Understand JWT Reserved Claims

    master

    JSON Web Tokens (JWT) are a type of JSON Web Signature (JWS) that use a standardized set of reserved claims. When working with JWTs in python-jose, you can include these claims to control token validity and identity:

    • 'exp' (Expiration): An int representing the time after which the token is invalid.
    • 'nbf' (Not Before): An int representing the time before which the token is invalid.
    • 'iss' (Issuer): A str identifying the principal that issued the JWT.
    • 'aud' (Audience): A str or list(str) identifying the intended recipient of the JWT.
    • 'iat' (Issued At): An int representing the time at which the JWT was issued.
  2. Select a cryptographic backend for python-jose

    master

    As of version 3.3.0, python-jose supports three backends. You select a backend by installing the corresponding extra. If no extra is selected, the native-python backend is used. Note that native-python is always installed due to setuptools complexities, but other backends take precedence if installed.

    Available Backends

    • cryptography (Recommended): Uses pyca/cryptography.
      • Installation: pip install python-jose[cryptography]
      • Note: If this is installed, it is selected over all other backends.
    • pycryptodome: Uses pycryptodome for all operations.
      • Installation: pip install python-jose[pycryptodome]
    • native-python: Uses python-rsa and python-ecdsa.
      • Installation: pip install python-jose
      • Limitation: This backend cannot process certificates.
    $ pip install python-jose[cryptography]
  3. Convert X.509 certificates to public keys

    master

    python-jose requires public keys rather than X.509 certificates. If you have an X.509 certificate (cert.pem) and need to convert it to a public key format that python-jose can consume, use the openssl command line tool.

    > openssl x509 -pubkey -noout < cert.pem
  4. Install python-jose with the recommended cryptography backend

    master

    To use the recommended cryptographic backend which utilizes pyca/cryptography, install python-jose with the [cryptography] extra. This backend is preferred over others if present and supports all operations.

    $ pip install python-jose[cryptography]
  5. Verify token signatures using JSON Web Keys (JWK)

    master

    You can verify a token's signature by constructing a key object from a JWK dictionary using jwk.construct() and then calling the .verify() method on that object.

    To perform verification:

    1. Construct the key object from the JWK (e.g., an HMAC key with kty: "oct").
    2. Split the JWT into the message (header + payload) and the encoded_sig.
    3. Decode the signature using base64url_decode.
    4. Call key.verify(message, decoded_sig).
    >>> from jose import jwk
    >>> from jose.utils import base64url_decode
    >>>
    >>> token = "eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZjMxNGJjNzAzNyJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0"
    >>> hmac_key = {
        "kty": "oct",
        "kid": "018c0ae5-4d9b-471b-bfd6-eef314bc7037",
        "use": "sig",
        "alg": "HS256",
        "k": "hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg"
    }
    >>>
    >>> key = jwk.construct(hmac_key)
    >>>
    >>> message, encoded_sig = token.rsplit('.', 1)
    >>> decoded_sig = base64url_decode(encoded_sig.encode())
    >>> key.verify(message, decoded_sig)
  6. Encrypt a payload with JWE

    master

    Use jose.jwe.encrypt to encrypt a payload. You must provide the payload, the key, and specify the algorithm (key management) and encryption (content encryption) parameters.

    from jose import jwe
    jwe.encrypt('Hello, World!', 'asecret128bitkey', algorithm='dir', encryption='A128GCM')
    # Returns a compact URL-safe string
  7. Decrypt a JWE payload

    master

    Use jose.jwe.decrypt to decrypt a compact JWE string. Provide the encrypted string and the key used for encryption.

    from jose import jwe
    jwe.decrypt('eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..McILMB3dYsNJSuhcDzQshA.OfX9H_mcUpHDeRM4IA.CcnTWqaqxNsjT4eCaUABSg', 'asecret128bitkey')
    # Returns 'Hello, World!'
  8. Sign tokens with JSON Web Signature (JWS)

    master

    Use jws.sign() to digitally sign a JSON-encoded object. You must provide the payload (a dictionary), a key (secret or private key), and specify the algorithm used for the signature.

    from jose import jws
    signed = jws.sign({'a': 'b'}, 'secret', algorithm='HS256')
  9. Supported JWE Key Management Algorithms

    master

    JWE supports various key management algorithms to determine how the content encryption key is wrapped or used. These include direct use of a key, RSA-based wrapping, or AES Key Wrap.

    | Algorithm Value | Key Wrap Algorithm |
    |-----------------+----------------------------------------------------|
    | DIR             | Direct (no key wrap)                               |
    | RSA1-5          | RSAES with PKCS1 v1.5                              |
    | RSA-OAEP        | RSAES OAEP using default parameters               |
    | RSA-OAEP-256    | RSAES OAEP using SHA-256 and MGF1 with SHA-256      |
    | A128KW          | AES Key Wrap with default IV using 128-bit key      |
    | A192KW          | AES Key Wrap with default IV using 192-bit key      |
    | A256KW          | AES Key Wrap with default IV using 256-bit key      |
  10. Supported JWS algorithms

    master

    The following algorithms are supported for JSON Web Signatures (JWS):

    | Algorithm Value | Digital Signature or MAC Algorithm |
    |-----------------|--------------------------------------|
    | HS256           | HMAC using SHA-256 hash algorithm     |
    | HS384           | HMAC using SHA-384 hash algorithm     |
    | HS512           | HMAC using SHA-512 hash algorithm     |
    | RS256           | RSASSA using SHA-256 hash algorithm   |
    | RS384           | RSASSA using SHA-384 hash algorithm   |
    | RS512           | RSASSA using SHA-512 hash algorithm   |
    | ES256           | ECDSA using SHA-256 hash algorithm    |
    | ES384           | ECDSA using SHA-384 hash algorithm    |
    | ES512           | ECDSA using SHA-512 hash algorithm    |