or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# python-jose

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: python-jose

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install python-jose[cryptography]`

10

11

## Core Imports

12

13

```python

14

from jose import jwt, jws, jwe, jwk

15

from jose.constants import ALGORITHMS

16

from jose.exceptions import JOSEError, JWTError, JWSError, JWEError, ExpiredSignatureError

17

```

18

19

Individual module imports:

20

21

```python

22

from jose.jwt import encode, decode, get_unverified_header, get_unverified_claims

23

from jose.jws import sign, verify, get_unverified_header, get_unverified_claims

24

from jose.jwe import encrypt, decrypt, get_unverified_header

25

from jose.jwk import construct, get_key

26

```

27

28

## Basic Usage

29

30

```python

31

from jose import jwt

32

from jose.constants import ALGORITHMS

33

34

# Encode a JWT

35

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

36

37

# Decode and verify a JWT

38

claims = jwt.decode(token, 'secret', algorithms=[ALGORITHMS.HS256])

39

print(claims) # {'user': 'john', 'exp': 1234567890}

40

41

# Handle different key formats

42

rsa_key = """-----BEGIN PUBLIC KEY-----

43

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...

44

-----END PUBLIC KEY-----"""

45

46

token = jwt.encode({'user': 'jane'}, rsa_key, algorithm=ALGORITHMS.RS256)

47

claims = jwt.decode(token, rsa_key, algorithms=[ALGORITHMS.RS256])

48

```

49

50

## Architecture

51

52

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

53

54

- **JWT Module**: High-level JSON Web Token operations with automatic claim validation

55

- **JWS Module**: Low-level JSON Web Signature operations for signing and verification

56

- **JWE Module**: JSON Web Encryption operations for content encryption and decryption

57

- **JWK Module**: JSON Web Key management for handling various key formats and types

58

59

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.

60

61

## Capabilities

62

63

### JWT Operations

64

65

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

66

67

```python { .api }

68

def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):

69

"""

70

Encodes a claims set and returns a JWT string.

71

72

Args:

73

claims (dict): A claims set to sign

74

key (str or dict): The key to use for signing

75

algorithm (str): The algorithm to use for signing (default: HS256)

76

headers (dict, optional): Additional headers

77

access_token (str, optional): For 'at_hash' claim calculation

78

79

Returns:

80

str: The JWT token string

81

"""

82

83

def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None):

84

"""

85

Decodes and verifies a JWT token.

86

87

Args:

88

token (str): The JWT token to decode

89

key (str or dict or list): The verification key(s)

90

algorithms (str or list): Allowed algorithms for verification

91

options (dict, optional): Verification options

92

audience (str, optional): Expected audience claim

93

issuer (str or list, optional): Expected issuer claim(s)

94

subject (str, optional): Expected subject claim

95

access_token (str, optional): For 'at_hash' verification

96

97

Returns:

98

dict: The decoded payload claims

99

"""

100

101

def get_unverified_header(token):

102

"""Get JWT header without verification."""

103

104

def get_unverified_claims(token):

105

"""Get JWT payload claims without verification."""

106

```

107

108

[JWT Operations](./jwt-operations.md)

109

110

### JWS Operations

111

112

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

113

114

```python { .api }

115

def sign(payload, key, headers=None, algorithm='HS256'):

116

"""

117

Signs a payload and returns a JWS string.

118

119

Args:

120

payload (str or dict): A payload to sign

121

key (str or dict): The key to use for signing

122

headers (dict, optional): Additional headers

123

algorithm (str): The algorithm to use for signing

124

125

Returns:

126

bytes: The JWS token

127

"""

128

129

def verify(token, key, algorithms, verify=True):

130

"""

131

Verifies a JWS token and returns the payload.

132

133

Args:

134

token (str or bytes): The JWS token to verify

135

key (str or dict or list): The verification key(s)

136

algorithms (str or list): Allowed verification algorithms

137

verify (bool): Whether to verify the signature

138

139

Returns:

140

bytes: The verified payload

141

"""

142

143

def get_unverified_header(token):

144

"""Get JWS header without verification."""

145

146

def get_unverified_claims(token):

147

"""Get JWS payload without verification."""

148

```

149

150

[JWS Operations](./jws-operations.md)

151

152

### JWE Operations

153

154

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

155

156

```python { .api }

157

def encrypt(plaintext, key, encryption='A256GCM', algorithm='dir', zip=None, cty=None, kid=None):

158

"""

159

Encrypts plaintext and returns a JWE string.

160

161

Args:

162

plaintext (bytes): Data to encrypt

163

key (str or bytes): The encryption key

164

encryption (str): Content encryption algorithm (default: A256GCM)

165

algorithm (str): Key encryption algorithm (default: dir)

166

zip (str, optional): Compression algorithm

167

cty (str, optional): Content type header

168

kid (str, optional): Key ID header

169

170

Returns:

171

bytes: The JWE token

172

"""

173

174

def decrypt(jwe_str, key):

175

"""

176

Decrypts JWE token and returns plaintext.

177

178

Args:

179

jwe_str (str or bytes): The JWE token to decrypt

180

key (str or bytes): The decryption key

181

182

Returns:

183

bytes: The decrypted plaintext

184

"""

185

186

def get_unverified_header(jwe_str):

187

"""Get JWE header without verification."""

188

```

189

190

[JWE Operations](./jwe-operations.md)

191

192

### JWK Management

193

194

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

195

196

```python { .api }

197

def construct(key_data, algorithm=None):

198

"""

199

Constructs a JWK from key data.

200

201

Args:

202

key_data (str or bytes or dict): The key material or JWK dict

203

algorithm (str, optional): Algorithm specification

204

205

Returns:

206

Key: The constructed key object

207

"""

208

209

def get_key(algorithm):

210

"""

211

Get key class for algorithm.

212

213

Args:

214

algorithm (str): The algorithm name

215

216

Returns:

217

type or None: The key class or None if not found

218

"""

219

220

class Key:

221

"""Base key class for all key implementations."""

222

223

def sign(self, msg):

224

"""Sign a message (abstract method)."""

225

226

def verify(self, msg, sig):

227

"""Verify a signature (abstract method)."""

228

```

229

230

[JWK Management](./jwk-management.md)

231

232

### Constants and Algorithms

233

234

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

235

236

```python { .api }

237

# Digital Signature Algorithms

238

ALGORITHMS.HS256 # HMAC SHA-256

239

ALGORITHMS.HS384 # HMAC SHA-384

240

ALGORITHMS.HS512 # HMAC SHA-512

241

ALGORITHMS.RS256 # RSA PKCS#1 SHA-256

242

ALGORITHMS.RS384 # RSA PKCS#1 SHA-384

243

ALGORITHMS.RS512 # RSA PKCS#1 SHA-512

244

ALGORITHMS.ES256 # ECDSA P-256 SHA-256

245

ALGORITHMS.ES384 # ECDSA P-384 SHA-384

246

ALGORITHMS.ES512 # ECDSA P-521 SHA-512

247

248

# Content Encryption Algorithms

249

ALGORITHMS.A128GCM # AES-128-GCM

250

ALGORITHMS.A192GCM # AES-192-GCM

251

ALGORITHMS.A256GCM # AES-256-GCM

252

ALGORITHMS.A128CBC_HS256 # AES-128-CBC + HMAC-SHA-256

253

ALGORITHMS.A192CBC_HS384 # AES-192-CBC + HMAC-SHA-384

254

ALGORITHMS.A256CBC_HS512 # AES-256-CBC + HMAC-SHA-512

255

256

# Key Encryption Algorithms

257

ALGORITHMS.DIR # Direct encryption

258

ALGORITHMS.RSA1_5 # RSA PKCS#1 v1.5

259

ALGORITHMS.RSA_OAEP # RSA OAEP

260

ALGORITHMS.A128KW # AES-128 Key Wrap

261

ALGORITHMS.A192KW # AES-192 Key Wrap

262

ALGORITHMS.A256KW # AES-256 Key Wrap

263

```

264

265

[Constants and Algorithms](./constants-algorithms.md)

266

267

## Error Handling

268

269

The library provides specific exception types for different error conditions:

270

271

```python { .api }

272

class JOSEError(Exception):

273

"""Base exception for all JOSE errors."""

274

275

class JWTError(JOSEError):

276

"""JWT-specific errors."""

277

278

class JWSError(JOSEError):

279

"""JWS-specific errors."""

280

281

class JWEError(JOSEError):

282

"""JWE-specific errors."""

283

284

class JWKError(JOSEError):

285

"""JWK-specific errors."""

286

287

class ExpiredSignatureError(JWTError):

288

"""JWT expired signature errors."""

289

```

290

291

Common error handling patterns:

292

293

```python

294

from jose import jwt

295

from jose.exceptions import JWTError, ExpiredSignatureError

296

297

try:

298

claims = jwt.decode(token, key, algorithms=['HS256'])

299

except ExpiredSignatureError:

300

print("Token has expired")

301

except JWTError as e:

302

print(f"Token validation failed: {e}")

303

```