or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

constants-algorithms.mdindex.mdjwe-operations.mdjwk-management.mdjws-operations.mdjwt-operations.md
tile.json

tessl/pypi-python-jose

JOSE implementation in Python providing JWT, JWS, JWE, and JWK functionality with multiple cryptographic backends.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-jose@3.5.x

To install, run

npx @tessl/cli install tessl/pypi-python-jose@3.5.0

index.mddocs/

python-jose

A comprehensive Python library implementing the JOSE (JavaScript Object Signing and Encryption) technologies, including JSON Web Tokens (JWT), JSON Web Signature (JWS), JSON Web Encryption (JWE), and JSON Web Key (JWK) specifications. The library provides multiple cryptographic backends for flexibility and security, with support for a wide range of algorithms and key formats.

Package Information

  • Package Name: python-jose
  • Package Type: pypi
  • Language: Python
  • Installation: pip install python-jose[cryptography]

Core Imports

from jose import jwt, jws, jwe, jwk
from jose.constants import ALGORITHMS
from jose.exceptions import JOSEError, JWTError, JWSError, JWEError, ExpiredSignatureError

Individual module imports:

from jose.jwt import encode, decode, get_unverified_header, get_unverified_claims
from jose.jws import sign, verify, get_unverified_header, get_unverified_claims
from jose.jwe import encrypt, decrypt, get_unverified_header
from jose.jwk import construct, get_key

Basic Usage

from jose import jwt
from jose.constants import ALGORITHMS

# Encode a JWT
token = jwt.encode({'user': 'john', 'exp': 1234567890}, 'secret', algorithm=ALGORITHMS.HS256)

# Decode and verify a JWT
claims = jwt.decode(token, 'secret', algorithms=[ALGORITHMS.HS256])
print(claims)  # {'user': 'john', 'exp': 1234567890}

# Handle different key formats
rsa_key = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----"""

token = jwt.encode({'user': 'jane'}, rsa_key, algorithm=ALGORITHMS.RS256)
claims = jwt.decode(token, rsa_key, algorithms=[ALGORITHMS.RS256])

Architecture

The python-jose library is organized into four main functional areas:

  • JWT Module: High-level JSON Web Token operations with automatic claim validation
  • JWS Module: Low-level JSON Web Signature operations for signing and verification
  • JWE Module: JSON Web Encryption operations for content encryption and decryption
  • JWK Module: JSON Web Key management for handling various key formats and types

The library supports multiple cryptographic backends (cryptography, pycryptodome, native-python) and automatically selects the most secure available backend, with pyca/cryptography being preferred for production use.

Capabilities

JWT Operations

High-level JSON Web Token functionality for encoding, decoding, and validating JWT tokens with comprehensive claim validation and flexible key handling.

def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
    """
    Encodes a claims set and returns a JWT string.
    
    Args:
        claims (dict): A claims set to sign
        key (str or dict): The key to use for signing
        algorithm (str): The algorithm to use for signing (default: HS256)
        headers (dict, optional): Additional headers
        access_token (str, optional): For 'at_hash' claim calculation
    
    Returns:
        str: The JWT token string
    """

def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None):
    """
    Decodes and verifies a JWT token.
    
    Args:
        token (str): The JWT token to decode
        key (str or dict or list): The verification key(s)
        algorithms (str or list): Allowed algorithms for verification
        options (dict, optional): Verification options
        audience (str, optional): Expected audience claim
        issuer (str or list, optional): Expected issuer claim(s)
        subject (str, optional): Expected subject claim
        access_token (str, optional): For 'at_hash' verification
    
    Returns:
        dict: The decoded payload claims
    """

def get_unverified_header(token):
    """Get JWT header without verification."""

def get_unverified_claims(token):
    """Get JWT payload claims without verification."""

JWT Operations

JWS Operations

Low-level JSON Web Signature functionality for signing payloads and verifying signatures with support for multiple algorithms and key formats.

def sign(payload, key, headers=None, algorithm='HS256'):
    """
    Signs a payload and returns a JWS string.
    
    Args:
        payload (str or dict): A payload to sign
        key (str or dict): The key to use for signing
        headers (dict, optional): Additional headers
        algorithm (str): The algorithm to use for signing
    
    Returns:
        bytes: The JWS token
    """

def verify(token, key, algorithms, verify=True):
    """
    Verifies a JWS token and returns the payload.
    
    Args:
        token (str or bytes): The JWS token to verify
        key (str or dict or list): The verification key(s)
        algorithms (str or list): Allowed verification algorithms
        verify (bool): Whether to verify the signature
    
    Returns:
        bytes: The verified payload
    """

def get_unverified_header(token):
    """Get JWS header without verification."""

def get_unverified_claims(token):
    """Get JWS payload without verification."""

JWS Operations

JWE Operations

JSON Web Encryption functionality for encrypting and decrypting content using various encryption algorithms and key management methods.

def encrypt(plaintext, key, encryption='A256GCM', algorithm='dir', zip=None, cty=None, kid=None):
    """
    Encrypts plaintext and returns a JWE string.
    
    Args:
        plaintext (bytes): Data to encrypt
        key (str or bytes): The encryption key
        encryption (str): Content encryption algorithm (default: A256GCM)
        algorithm (str): Key encryption algorithm (default: dir)
        zip (str, optional): Compression algorithm
        cty (str, optional): Content type header
        kid (str, optional): Key ID header
    
    Returns:
        bytes: The JWE token
    """

def decrypt(jwe_str, key):
    """
    Decrypts JWE token and returns plaintext.
    
    Args:
        jwe_str (str or bytes): The JWE token to decrypt
        key (str or bytes): The decryption key
    
    Returns:
        bytes: The decrypted plaintext
    """

def get_unverified_header(jwe_str):
    """Get JWE header without verification."""

JWE Operations

JWK Management

JSON Web Key functionality for constructing, managing, and converting between different key formats and representations.

def construct(key_data, algorithm=None):
    """
    Constructs a JWK from key data.
    
    Args:
        key_data (str or bytes or dict): The key material or JWK dict
        algorithm (str, optional): Algorithm specification
    
    Returns:
        Key: The constructed key object
    """

def get_key(algorithm):
    """
    Get key class for algorithm.
    
    Args:
        algorithm (str): The algorithm name
    
    Returns:
        type or None: The key class or None if not found
    """

class Key:
    """Base key class for all key implementations."""
    
    def sign(self, msg):
        """Sign a message (abstract method)."""
    
    def verify(self, msg, sig):
        """Verify a signature (abstract method)."""

JWK Management

Constants and Algorithms

Core algorithm constants and configuration options used throughout the JOSE implementations.

# Digital Signature Algorithms
ALGORITHMS.HS256  # HMAC SHA-256
ALGORITHMS.HS384  # HMAC SHA-384  
ALGORITHMS.HS512  # HMAC SHA-512
ALGORITHMS.RS256  # RSA PKCS#1 SHA-256
ALGORITHMS.RS384  # RSA PKCS#1 SHA-384
ALGORITHMS.RS512  # RSA PKCS#1 SHA-512
ALGORITHMS.ES256  # ECDSA P-256 SHA-256
ALGORITHMS.ES384  # ECDSA P-384 SHA-384
ALGORITHMS.ES512  # ECDSA P-521 SHA-512

# Content Encryption Algorithms
ALGORITHMS.A128GCM  # AES-128-GCM
ALGORITHMS.A192GCM  # AES-192-GCM
ALGORITHMS.A256GCM  # AES-256-GCM
ALGORITHMS.A128CBC_HS256  # AES-128-CBC + HMAC-SHA-256
ALGORITHMS.A192CBC_HS384  # AES-192-CBC + HMAC-SHA-384
ALGORITHMS.A256CBC_HS512  # AES-256-CBC + HMAC-SHA-512

# Key Encryption Algorithms
ALGORITHMS.DIR      # Direct encryption
ALGORITHMS.RSA1_5   # RSA PKCS#1 v1.5
ALGORITHMS.RSA_OAEP # RSA OAEP
ALGORITHMS.A128KW   # AES-128 Key Wrap
ALGORITHMS.A192KW   # AES-192 Key Wrap
ALGORITHMS.A256KW   # AES-256 Key Wrap

Constants and Algorithms

Error Handling

The library provides specific exception types for different error conditions:

class JOSEError(Exception):
    """Base exception for all JOSE errors."""

class JWTError(JOSEError):
    """JWT-specific errors."""

class JWSError(JOSEError):
    """JWS-specific errors."""

class JWEError(JOSEError):
    """JWE-specific errors."""

class JWKError(JOSEError):
    """JWK-specific errors."""

class ExpiredSignatureError(JWTError):
    """JWT expired signature errors."""

Common error handling patterns:

from jose import jwt
from jose.exceptions import JWTError, ExpiredSignatureError

try:
    claims = jwt.decode(token, key, algorithms=['HS256'])
except ExpiredSignatureError:
    print("Token has expired")
except JWTError as e:
    print(f"Token validation failed: {e}")