or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-cryptography

Cryptographic recipes and primitives for Python developers

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/cryptography@45.0.x

To install, run

npx @tessl/cli install tessl/pypi-cryptography@45.0.0

0

# Cryptography

1

2

A comprehensive Python cryptographic library providing cryptographic recipes and primitives to Python developers. The cryptography package serves as Python's cryptographic standard library, offering both high-level recipes for common cryptographic operations and low-level interfaces to cryptographic algorithms.

3

4

## Package Information

5

6

- **Package Name**: cryptography

7

- **Language**: Python

8

- **Installation**: `pip install cryptography`

9

- **Python Support**: Python 3.7+ and PyPy3

10

- **Optional Dependencies**: `pip install cryptography[ssh]` for SSH key support

11

12

## Core Imports

13

14

```python

15

import cryptography

16

from cryptography import __version__, __author__, __copyright__

17

```

18

19

Common high-level imports:

20

21

```python

22

from cryptography.fernet import Fernet, MultiFernet, InvalidToken

23

from cryptography import x509

24

from cryptography.exceptions import (

25

InvalidSignature, InvalidKey, UnsupportedAlgorithm,

26

AlreadyFinalized, InvalidTag

27

)

28

```

29

30

Low-level hazmat imports (use with caution):

31

32

```python

33

from cryptography.hazmat.primitives import hashes, serialization

34

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

35

from cryptography.hazmat.primitives.asymmetric import rsa, dsa, ec, padding

36

from cryptography.hazmat.primitives.kdf import pbkdf2, hkdf

37

```

38

39

## Basic Usage

40

41

```python

42

from cryptography.fernet import Fernet

43

44

# Generate a key for symmetric encryption

45

key = Fernet.generate_key()

46

fernet = Fernet(key)

47

48

# Encrypt data

49

message = b"Secret message"

50

encrypted = fernet.encrypt(message)

51

52

# Decrypt data

53

decrypted = fernet.decrypt(encrypted)

54

print(decrypted) # b"Secret message"

55

56

# X.509 certificate handling

57

from cryptography import x509

58

from cryptography.hazmat.primitives import serialization

59

60

# Load a certificate from PEM data

61

cert = x509.load_pem_x509_certificate(pem_data)

62

print(cert.subject)

63

print(cert.public_key())

64

```

65

66

## Architecture

67

68

The cryptography package follows a layered architecture separating safe high-level APIs from expert-level primitives:

69

70

- **High-level APIs**: Safe, ready-to-use cryptographic functions (Fernet, X.509)

71

- **Hazmat Layer**: Low-level "hazardous materials" primitives requiring expert knowledge

72

- **Backend Abstraction**: OpenSSL backend with Rust integration for performance

73

- **Standards Compliance**: Implements cryptographic standards and best practices

74

75

This design ensures developers can use cryptography safely at the appropriate level for their expertise while maintaining access to full cryptographic functionality.

76

77

## Capabilities

78

79

### Symmetric Encryption (Fernet)

80

81

High-level symmetric encryption using authenticated encryption. Provides secure, simple encryption/decryption with built-in authentication and key rotation support.

82

83

```python { .api }

84

class Fernet:

85

def __init__(self, key: bytes | str, backend: typing.Any = None): ...

86

@classmethod

87

def generate_key(cls) -> bytes: ...

88

def encrypt(self, data: bytes) -> bytes: ...

89

def encrypt_at_time(self, data: bytes, current_time: int) -> bytes: ...

90

def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes: ...

91

def decrypt_at_time(self, token: bytes | str, ttl: int, current_time: int) -> bytes: ...

92

def extract_timestamp(self, token: bytes | str) -> int: ...

93

94

class MultiFernet:

95

def __init__(self, fernets: Iterable[Fernet]): ...

96

def encrypt(self, msg: bytes) -> bytes: ...

97

def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes: ...

98

def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes: ...

99

def decrypt_at_time(self, msg: bytes | str, ttl: int, current_time: int) -> bytes: ...

100

def rotate(self, msg: bytes | str) -> bytes: ...

101

def extract_timestamp(self, msg: bytes | str) -> int: ...

102

103

class InvalidToken(Exception): ...

104

```

105

106

[Symmetric Encryption](./symmetric-encryption.md)

107

108

### X.509 Certificates

109

110

Comprehensive X.509 certificate handling including certificate creation, parsing, validation, and extension management. Supports certificate signing requests, certificate revocation lists, and certificate verification.

111

112

```python { .api }

113

class Certificate:

114

def public_key(self): ...

115

def subject(self) -> Name: ...

116

def issuer(self) -> Name: ...

117

def serial_number(self) -> int: ...

118

119

class CertificateBuilder:

120

def subject_name(self, name: Name) -> 'CertificateBuilder': ...

121

def issuer_name(self, name: Name) -> 'CertificateBuilder': ...

122

def public_key(self, key) -> 'CertificateBuilder': ...

123

def sign(self, private_key, algorithm) -> Certificate: ...

124

125

def load_pem_x509_certificate(data: bytes) -> Certificate: ...

126

def load_der_x509_certificate(data: bytes) -> Certificate: ...

127

```

128

129

[X.509 Certificates](./x509-certificates.md)

130

131

### Hash Functions

132

133

Cryptographic hash functions including SHA family, SHA-3, BLAKE2, and more. Provides both one-shot hashing and incremental hash contexts.

134

135

```python { .api }

136

class Hash:

137

def __init__(self, algorithm, backend=None): ...

138

def update(self, data: bytes) -> None: ...

139

def finalize(self) -> bytes: ...

140

141

class SHA256: ...

142

class SHA3_256: ...

143

class BLAKE2b:

144

def __init__(self, digest_size: int): ...

145

```

146

147

[Hash Functions](./hash-functions.md)

148

149

### Symmetric Ciphers

150

151

Low-level symmetric encryption algorithms including AES, ChaCha20, and cipher modes. Provides building blocks for custom cryptographic protocols.

152

153

```python { .api }

154

class Cipher:

155

def __init__(self, algorithm, mode, backend=None): ...

156

def encryptor(self) -> CipherContext: ...

157

def decryptor(self) -> CipherContext: ...

158

159

class AES:

160

def __init__(self, key: bytes): ...

161

162

class ChaCha20:

163

def __init__(self, key: bytes, nonce: bytes): ...

164

```

165

166

[Symmetric Ciphers](./symmetric-ciphers.md)

167

168

### AEAD Ciphers

169

170

Authenticated Encryption with Associated Data providing encryption and authentication in a single operation. Includes AES-GCM, ChaCha20-Poly1305, and other modern AEAD algorithms.

171

172

```python { .api }

173

class AESGCM:

174

def __init__(self, key: bytes): ...

175

def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...

176

def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...

177

178

class ChaCha20Poly1305:

179

def __init__(self, key: bytes): ...

180

def encrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...

181

def decrypt(self, nonce: bytes, data: bytes, associated_data: bytes = None) -> bytes: ...

182

```

183

184

[AEAD Ciphers](./aead-ciphers.md)

185

186

### Asymmetric Cryptography

187

188

Public-key cryptography including RSA, DSA, ECDSA, EdDSA, and key exchange algorithms. Supports key generation, digital signatures, and encryption.

189

190

```python { .api }

191

def generate_private_key(public_exponent: int, key_size: int) -> RSAPrivateKey: ...

192

193

class RSAPrivateKey:

194

def public_key(self) -> RSAPublicKey: ...

195

def sign(self, data: bytes, padding, algorithm): ...

196

def private_bytes(self, encoding, format, encryption_algorithm): ...

197

198

class RSAPublicKey:

199

def verify(self, signature: bytes, data: bytes, padding, algorithm): ...

200

def encrypt(self, plaintext: bytes, padding): ...

201

```

202

203

[Asymmetric Cryptography](./asymmetric-cryptography.md)

204

205

### Key Derivation Functions

206

207

Password-based and key-based derivation functions for generating cryptographic keys from passwords or other key material. Includes PBKDF2, HKDF, Scrypt, and Argon2.

208

209

```python { .api }

210

class PBKDF2HMAC:

211

def __init__(self, algorithm, length: int, salt: bytes, iterations: int): ...

212

def derive(self, key_material: bytes) -> bytes: ...

213

def verify(self, key_material: bytes, expected_key: bytes) -> None: ...

214

215

class HKDF:

216

def __init__(self, algorithm, length: int, salt: bytes = None, info: bytes = None): ...

217

def derive(self, key_material: bytes) -> bytes: ...

218

```

219

220

[Key Derivation Functions](./key-derivation.md)

221

222

### Key Serialization

223

224

Serialization and deserialization of cryptographic keys in various formats including PEM, DER, and SSH formats. Supports both public and private keys with optional encryption.

225

226

```python { .api }

227

def load_pem_private_key(data: bytes, password: bytes = None) -> PrivateKey: ...

228

def load_pem_public_key(data: bytes) -> PublicKey: ...

229

def load_ssh_private_key(data: bytes, password: bytes = None) -> PrivateKey: ...

230

231

class Encoding:

232

PEM: Encoding

233

DER: Encoding

234

235

class PrivateFormat:

236

PKCS8: PrivateFormat

237

TraditionalOpenSSL: PrivateFormat

238

```

239

240

[Key Serialization](./key-serialization.md)

241

242

### Message Authentication

243

244

Message authentication codes and digital signatures for ensuring data integrity and authenticity. Includes HMAC, CMAC, and Poly1305.

245

246

```python { .api }

247

class HMAC:

248

def __init__(self, key: bytes, algorithm): ...

249

def update(self, data: bytes) -> None: ...

250

def finalize(self) -> bytes: ...

251

def verify(self, signature: bytes) -> None: ...

252

253

class CMAC:

254

def __init__(self, key: bytes, algorithm): ...

255

def update(self, data: bytes) -> None: ...

256

def finalize(self) -> bytes: ...

257

```

258

259

[Message Authentication](./message-authentication.md)

260

261

### Two-Factor Authentication

262

263

Time-based and HMAC-based one-time password (OTP) generation and verification for implementing two-factor authentication systems.

264

265

```python { .api }

266

class TOTP:

267

def __init__(self, key: bytes, length: int, algorithm, time_step: int): ...

268

def generate(self, time: int) -> bytes: ...

269

def verify(self, totp: bytes, time: int) -> None: ...

270

271

class HOTP:

272

def __init__(self, key: bytes, length: int, algorithm): ...

273

def generate(self, counter: int) -> bytes: ...

274

def verify(self, hotp: bytes, counter: int) -> None: ...

275

```

276

277

[Two-Factor Authentication](./two-factor-auth.md)

278

279

### Cryptographic Utilities

280

281

Additional utilities including constant-time operations and AES key wrapping functionality for secure key storage and timing attack prevention.

282

283

```python { .api }

284

def bytes_eq(a: bytes, b: bytes) -> bool: ...

285

286

def aes_key_wrap(wrapping_key: bytes, key_to_wrap: bytes) -> bytes: ...

287

def aes_key_unwrap(wrapping_key: bytes, wrapped_key: bytes) -> bytes: ...

288

def aes_key_wrap_with_padding(wrapping_key: bytes, key_to_wrap: bytes) -> bytes: ...

289

def aes_key_unwrap_with_padding(wrapping_key: bytes, wrapped_key: bytes) -> bytes: ...

290

```

291

292

[Cryptographic Utilities](./utilities.md)

293

294

## Package Information API

295

296

Package-level metadata and version information:

297

298

```python { .api }

299

__version__: str # "45.0.7"

300

__author__: str # "The Python Cryptographic Authority and individual contributors"

301

__copyright__: str # "Copyright 2013-2025 {__author__}"

302

```

303

304

## Exception Handling

305

306

Common exceptions thrown by the cryptography library:

307

308

```python { .api }

309

# Core exceptions from cryptography.exceptions

310

class UnsupportedAlgorithm(Exception):

311

def __init__(self, message: str, reason: _Reasons | None = None): ...

312

313

class InvalidSignature(Exception): ...

314

class InvalidKey(Exception): ...

315

class InvalidTag(Exception): ...

316

class AlreadyFinalized(Exception): ...

317

class AlreadyUpdated(Exception): ...

318

class NotYetFinalized(Exception): ...

319

class InternalError(Exception):

320

def __init__(self, msg: str, err_code: list[rust_openssl.OpenSSLError]): ...

321

322

# Fernet-specific exception

323

class InvalidToken(Exception): ... # from cryptography.fernet

324

```

325

326

Most cryptographic operations can raise `InvalidSignature`, `InvalidKey`, or `UnsupportedAlgorithm` exceptions. Always handle these appropriately in production code.