or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cryptographic-hashing.mdcryptographic-protocols.mddigital-signatures.mdindex.mdinput-output-operations.mdmathematical-primitives.mdpublic-key-cryptography.mdsymmetric-encryption.mdutility-functions.md

cryptographic-protocols.mddocs/

0

# Cryptographic Protocols

1

2

High-level cryptographic protocols and constructions including key derivation functions, secret sharing schemes, and key exchange protocols. These protocols build upon primitive cryptographic functions to provide complete security solutions.

3

4

## Capabilities

5

6

### Key Derivation Functions (KDF)

7

8

Functions that derive cryptographic keys from passwords, shared secrets, or other key material with configurable security parameters and salt values.

9

10

```python { .api }

11

def scrypt(password, salt, key_len, N, r, p, num_keys=1):

12

"""

13

Scrypt key derivation function - memory-hard KDF resistant to specialized hardware attacks.

14

15

Parameters:

16

- password (bytes): Password or passphrase to derive key from

17

- salt (bytes): Salt value (recommend 16+ bytes)

18

- key_len (int): Length of derived key in bytes

19

- N (int): CPU/memory cost parameter (power of 2, e.g., 16384)

20

- r (int): Block size parameter (e.g., 8)

21

- p (int): Parallelization parameter (e.g., 1)

22

- num_keys (int): Number of keys to derive (default: 1)

23

24

Returns:

25

bytes or list of bytes: Derived key(s)

26

"""

27

28

def PBKDF2(password, salt, dkLen=16, count=1000, prf=None, hmac_hash_module=None):

29

"""

30

PBKDF2 key derivation function - widely supported password-based KDF.

31

32

Parameters:

33

- password (bytes): Password to derive key from

34

- salt (bytes): Salt value (recommend 16+ bytes)

35

- dkLen (int): Desired key length in bytes

36

- count (int): Iteration count (recommend 100,000+)

37

- prf (callable): Pseudorandom function (default: HMAC-SHA1)

38

- hmac_hash_module: Hash module for HMAC (e.g., SHA256)

39

40

Returns:

41

bytes: Derived key

42

"""

43

44

def HKDF(master, length, salt, hashmod, num_keys=1, context=b""):

45

"""

46

HKDF (HMAC-based Key Derivation Function) - extract and expand pattern for key derivation.

47

48

Parameters:

49

- master (bytes): Input key material (IKM)

50

- length (int): Length of output key material in bytes

51

- salt (bytes): Optional salt value (can be empty)

52

- hashmod: Hash algorithm module (e.g., SHA256)

53

- num_keys (int): Number of keys to derive

54

- context (bytes): Optional context and application specific information

55

56

Returns:

57

bytes or list of bytes: Derived key material

58

"""

59

60

def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):

61

"""

62

PBKDF1 key derivation function - legacy, limited output length.

63

64

Parameters:

65

- password (bytes): Password to derive key from

66

- salt (bytes): 8-byte salt value

67

- dkLen (int): Desired key length (max 20 bytes for SHA-1)

68

- count (int): Iteration count

69

- hashAlgo: Hash algorithm (default: SHA-1)

70

71

Returns:

72

bytes: Derived key

73

"""

74

75

def bcrypt(password, cost, salt=None):

76

"""

77

Bcrypt password hashing function - adaptive hash function for passwords.

78

79

Parameters:

80

- password (bytes): Password to hash

81

- cost (int): Work factor (4-31, recommend 12+)

82

- salt (bytes): 16-byte salt (auto-generated if None)

83

84

Returns:

85

bytes: Bcrypt hash string

86

"""

87

88

def bcrypt_check(password, bcrypt_hash):

89

"""

90

Verify bcrypt password hash.

91

92

Parameters:

93

- password (bytes): Password to verify

94

- bcrypt_hash (bytes): Bcrypt hash to check against

95

96

Returns:

97

bool: True if password matches hash

98

"""

99

```

100

101

### Secret Sharing

102

103

Shamir's Secret Sharing scheme allowing a secret to be divided into shares where any subset of shares can reconstruct the original secret.

104

105

```python { .api }

106

class Shamir:

107

"""Shamir's Secret Sharing implementation."""

108

109

@staticmethod

110

def split(k, n, secret, ssss=False):

111

"""

112

Split secret into n shares where k shares are needed to reconstruct.

113

114

Parameters:

115

- k (int): Threshold - minimum shares needed to reconstruct secret

116

- n (int): Total number of shares to generate

117

- secret (bytes): Secret data to split (max 64 bytes)

118

- ssss (bool): Use SSSS format for compatibility

119

120

Returns:

121

list of tuples: [(share_index, share_data), ...] where share_index is 1-based

122

"""

123

124

@staticmethod

125

def combine(shares, ssss=False):

126

"""

127

Reconstruct secret from threshold number of shares.

128

129

Parameters:

130

- shares (list): List of (share_index, share_data) tuples

131

- ssss (bool): Interpret shares as SSSS format

132

133

Returns:

134

bytes: Reconstructed secret

135

136

Raises:

137

ValueError: If insufficient shares or shares are invalid

138

"""

139

```

140

141

### Key Exchange Protocols

142

143

Elliptic curve Diffie-Hellman key exchange using modern curves (X25519, X448) for establishing shared secrets.

144

145

```python { .api }

146

def import_x25519_public_key(encoded):

147

"""

148

Import X25519 public key for key exchange.

149

150

Parameters:

151

- encoded (bytes): 32-byte public key in binary format or PEM/DER

152

153

Returns:

154

ECC key object for X25519 curve

155

"""

156

157

def import_x25519_private_key(encoded, passphrase=None):

158

"""

159

Import X25519 private key.

160

161

Parameters:

162

- encoded (bytes): Private key in binary, PEM, or PKCS#8 format

163

- passphrase (bytes): Password for encrypted keys

164

165

Returns:

166

ECC key object for X25519 curve

167

"""

168

169

def import_x448_public_key(encoded):

170

"""

171

Import X448 public key for key exchange.

172

173

Parameters:

174

- encoded (bytes): 56-byte public key in binary format or PEM/DER

175

176

Returns:

177

ECC key object for X448 curve

178

"""

179

180

def import_x448_private_key(encoded, passphrase=None):

181

"""

182

Import X448 private key.

183

184

Parameters:

185

- encoded (bytes): Private key in binary, PEM, or PKCS#8 format

186

- passphrase (bytes): Password for encrypted keys

187

188

Returns:

189

ECC key object for X448 curve

190

"""

191

```

192

193

### HPKE (Hybrid Public Key Encryption)

194

195

Modern hybrid encryption combining public key cryptography with symmetric encryption for efficient encryption of longer messages.

196

197

```python { .api }

198

class MODE:

199

"""HPKE mode constants."""

200

BASE: int # Base mode

201

PSK: int # Pre-shared key mode

202

AUTH: int # Authenticated mode

203

AUTH_PSK: int # Authenticated + pre-shared key mode

204

205

class AEAD:

206

"""AEAD cipher interface for HPKE."""

207

208

def encrypt(self, plaintext: bytes, aad: bytes = b"") -> bytes:

209

"""Encrypt plaintext with additional authenticated data."""

210

211

def decrypt(self, ciphertext: bytes, aad: bytes = b"") -> bytes:

212

"""Decrypt ciphertext and verify additional authenticated data."""

213

214

class DeserializeError(Exception):

215

"""Exception raised when HPKE key deserialization fails."""

216

217

class MessageLimitReachedError(Exception):

218

"""Exception raised when HPKE message limit is exceeded."""

219

```

220

221

## Usage Examples

222

223

### Password-Based Key Derivation

224

```python

225

from Crypto.Protocol.KDF import PBKDF2, scrypt

226

from Crypto.Hash import SHA256

227

from Crypto.Random import get_random_bytes

228

229

# PBKDF2 for general password-based keys

230

password = b"user_password"

231

salt = get_random_bytes(16)

232

key = PBKDF2(password, salt, dkLen=32, count=100000, hmac_hash_module=SHA256)

233

234

# Scrypt for high-security applications

235

scrypt_key = scrypt(password, salt, key_len=32, N=16384, r=8, p=1)

236

237

# Verify password with bcrypt

238

from Crypto.Protocol.KDF import bcrypt, bcrypt_check

239

password_hash = bcrypt(password, cost=12)

240

is_valid = bcrypt_check(password, password_hash)

241

```

242

243

### Key Derivation from Shared Secret

244

```python

245

from Crypto.Protocol.KDF import HKDF

246

from Crypto.Hash import SHA256

247

248

# Derive keys from shared secret (e.g., from ECDH)

249

shared_secret = b"shared_key_material_from_ecdh"

250

salt = get_random_bytes(16)

251

info = b"application_context"

252

253

# Derive encryption and MAC keys

254

keys = HKDF(shared_secret, 64, salt, SHA256, num_keys=2, context=info)

255

encryption_key = keys[0][:32]

256

mac_key = keys[1][:32]

257

```

258

259

### Secret Sharing

260

```python

261

from Crypto.Protocol.SecretSharing import Shamir

262

263

# Split secret into 5 shares, requiring 3 to reconstruct

264

secret = b"top_secret_data_to_protect"

265

shares = Shamir.split(3, 5, secret)

266

267

print(f"Generated {len(shares)} shares:")

268

for idx, share_data in shares:

269

print(f"Share {idx}: {share_data.hex()}")

270

271

# Reconstruct secret from any 3 shares

272

selected_shares = shares[:3] # Use first 3 shares

273

reconstructed = Shamir.combine(selected_shares)

274

assert reconstructed == secret

275

```

276

277

### X25519 Key Exchange

278

```python

279

from Crypto.PublicKey import ECC

280

from Crypto.Protocol.DH import import_x25519_public_key, import_x25519_private_key

281

282

# Generate X25519 key pairs for Alice and Bob

283

alice_private = ECC.generate(curve='X25519')

284

bob_private = ECC.generate(curve='X25519')

285

286

# Exchange public keys

287

alice_public = alice_private.public_key()

288

bob_public = bob_private.public_key()

289

290

# Perform ECDH key agreement (both sides compute the same shared secret)

291

# Note: Actual ECDH computation requires additional implementation

292

# This example shows key management only

293

```

294

295

### Multiple Key Derivation

296

```python

297

from Crypto.Protocol.KDF import HKDF

298

from Crypto.Hash import SHA256

299

300

# Derive multiple keys for different purposes

301

master_secret = get_random_bytes(32)

302

salt = get_random_bytes(16)

303

304

# Derive 3 keys: encryption, MAC, and IV derivation

305

keys = HKDF(master_secret, 32, salt, SHA256, num_keys=3, context=b"app_v1.0")

306

encryption_key = keys[0]

307

mac_key = keys[1]

308

iv_key = keys[2]

309

```

310

311

## Security Parameters and Recommendations

312

313

### PBKDF2 Parameters

314

- **Iterations**: Minimum 100,000, prefer 600,000+ for new applications

315

- **Salt**: Minimum 16 bytes, unique per password

316

- **Hash**: SHA-256 or better (avoid SHA-1 for new applications)

317

318

### Scrypt Parameters

319

- **N (CPU/Memory cost)**: 16384 for interactive use, 1048576 for offline

320

- **r (Block size)**: 8 (standard value)

321

- **p (Parallelization)**: 1 for most applications

322

- **Salt**: Minimum 16 bytes, unique per password

323

324

### HKDF Parameters

325

- **Salt**: Should be random, can be empty for some applications

326

- **Info/Context**: Application-specific information for key separation

327

- **Hash**: SHA-256 or SHA-512 recommended

328

329

### Bcrypt Parameters

330

- **Cost**: Minimum 12, prefer 14+ for new applications

331

- **Salt**: Automatically handled by bcrypt implementation

332

333

### Secret Sharing Parameters

334

- **Threshold (k)**: Balance between security and availability

335

- **Total shares (n)**: Consider loss/compromise scenarios

336

- **Secret size**: Maximum 64 bytes per split operation

337

338

## Protocol Security Considerations

339

340

### Key Derivation Security

341

- Use appropriate iteration counts based on expected hardware

342

- Always use random, unique salts

343

- Consider memory-hard functions (scrypt) for password-based keys

344

- Separate keys for different purposes using different context info

345

346

### Secret Sharing Security

347

- Protect individual shares as sensitive data

348

- Consider threshold selection carefully (k-1 shares reveal nothing)

349

- Use secure channels for share distribution

350

- Implement proper share lifecycle management

351

352

### Key Exchange Security

353

- Verify public key authenticity to prevent man-in-the-middle attacks

354

- Use ephemeral keys for forward secrecy

355

- Combine with authentication mechanisms

356

- Validate curve points to prevent invalid curve attacks

357

358

## Error Handling

359

360

- `ValueError`: Invalid parameters, insufficient shares, or malformed input

361

- `TypeError`: Incorrect parameter types

362

- `OverflowError`: Parameters outside valid ranges

363

- `DeserializeError`: Invalid key formats in HPKE operations

364

- `MessageLimitReachedError`: HPKE message limits exceeded