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

public-key-cryptography.mddocs/

0

# Public Key Cryptography

1

2

Comprehensive public key cryptography implementation supporting RSA, DSA, ECC, and ElGamal algorithms. Provides key generation, import/export, and cryptographic operations with extensive format support and security features.

3

4

## Capabilities

5

6

### RSA (Rivest-Shamir-Adleman)

7

8

The most widely used public key algorithm, suitable for both encryption and digital signatures with configurable key sizes and security parameters.

9

10

```python { .api }

11

def generate(bits, randfunc=None, e=65537):

12

"""

13

Generate a new RSA key pair.

14

15

Parameters:

16

- bits (int): Key size in bits (minimum 1024, recommended 2048+)

17

- randfunc (callable): Random function (default: Crypto.Random.get_random_bytes)

18

- e (int): Public exponent (default: 65537)

19

20

Returns:

21

RsaKey object containing both private and public key

22

"""

23

24

def construct(rsa_components, consistency_check=True):

25

"""

26

Construct RSA key from mathematical components.

27

28

Parameters:

29

- rsa_components (tuple): (n, e) for public key or (n, e, d, p, q) for private key

30

- consistency_check (bool): Verify mathematical consistency

31

32

Returns:

33

RsaKey object

34

"""

35

36

def import_key(extern_key, passphrase=None):

37

"""

38

Import RSA key from external format.

39

40

Parameters:

41

- extern_key (bytes/str): Key data in PEM, DER, PKCS#1, PKCS#8, or OpenSSH format

42

- passphrase (bytes/str): Password for encrypted keys

43

44

Returns:

45

RsaKey object

46

"""

47

48

class RsaKey:

49

"""RSA key object with cryptographic operations."""

50

51

def has_private(self) -> bool:

52

"""Check if private key is present."""

53

54

def public_key(self):

55

"""Extract public key component."""

56

57

def export_key(self, format='PEM', **kwargs) -> bytes:

58

"""

59

Export key in specified format.

60

61

Parameters:

62

- format (str): 'PEM', 'DER', 'PKCS1', 'PKCS8', 'OpenSSH'

63

- passphrase (bytes): Password for private key encryption

64

- protection (str): Encryption algorithm for PKCS#8

65

66

Returns:

67

Exported key as bytes

68

"""

69

70

def encrypt(self, plaintext: bytes, padding) -> bytes:

71

"""Encrypt with public key (use PKCS1_OAEP.new() instead)."""

72

73

def decrypt(self, ciphertext: bytes, padding) -> bytes:

74

"""Decrypt with private key (use PKCS1_OAEP.new() instead)."""

75

76

def sign(self, msg_hash: bytes, padding) -> bytes:

77

"""Sign hash (use Signature modules instead)."""

78

79

def verify(self, msg_hash: bytes, signature: bytes, padding) -> bool:

80

"""Verify signature (use Signature modules instead)."""

81

82

# Key properties

83

size_in_bits(self) -> int: """Key size in bits."""

84

size_in_bytes(self) -> int: """Key size in bytes."""

85

n: int # Modulus

86

e: int # Public exponent

87

d: int # Private exponent (private keys only)

88

p: int # First prime factor (private keys only)

89

q: int # Second prime factor (private keys only)

90

91

oid: str # RSA algorithm OID

92

```

93

94

### ECC (Elliptic Curve Cryptography)

95

96

Modern public key cryptography based on elliptic curves, providing equivalent security to RSA with smaller key sizes and better performance.

97

98

```python { .api }

99

def generate(**kwargs):

100

"""

101

Generate new ECC key pair.

102

103

Parameters:

104

- curve (str): Curve name ('P-256', 'P-384', 'P-521', 'secp256k1', 'Ed25519', 'Ed448', etc.)

105

- randfunc (callable): Random function

106

107

Returns:

108

EccKey object

109

"""

110

111

def construct(**kwargs):

112

"""

113

Construct ECC key from parameters.

114

115

Parameters:

116

- curve (str): Curve name

117

- point_x (int): Public key X coordinate

118

- point_y (int): Public key Y coordinate

119

- d (int): Private key scalar (optional)

120

121

Returns:

122

EccKey object

123

"""

124

125

def import_key(encoded, passphrase=None, curve_name=None):

126

"""

127

Import ECC key from encoded format.

128

129

Parameters:

130

- encoded (bytes): Key in PEM, DER, SEC1, or PKCS#8 format

131

- passphrase (bytes): Password for encrypted keys

132

- curve_name (str): Explicit curve name if not in key data

133

134

Returns:

135

EccKey object

136

"""

137

138

class EccKey:

139

"""Elliptic curve key object."""

140

141

def has_private(self) -> bool:

142

"""Check if private key is present."""

143

144

def public_key(self):

145

"""Extract public key component."""

146

147

def export_key(self, **kwargs) -> bytes:

148

"""

149

Export key in specified format.

150

151

Parameters:

152

- format (str): 'PEM', 'DER', 'SEC1', 'PKCS8', 'OpenSSH'

153

- use_pkcs8 (bool): Use PKCS#8 for private keys

154

- passphrase (bytes): Encryption password

155

156

Returns:

157

Exported key as bytes

158

"""

159

160

# Key properties

161

curve: str # Curve name

162

pointQ: EccPoint # Public key point

163

d: int # Private scalar (private keys only)

164

165

class UnsupportedEccFeature(Exception):

166

"""Exception for unsupported ECC features."""

167

```

168

169

### DSA (Digital Signature Algorithm)

170

171

FIPS-approved algorithm designed specifically for digital signatures, based on discrete logarithm problem.

172

173

```python { .api }

174

def generate(bits, randfunc=None, domain=None):

175

"""

176

Generate new DSA key pair.

177

178

Parameters:

179

- bits (int): Key size in bits (1024, 2048, 3072)

180

- randfunc (callable): Random function

181

- domain (tuple): Optional (p, q, g) domain parameters

182

183

Returns:

184

DsaKey object

185

"""

186

187

def construct(tup, consistency_check=True):

188

"""

189

Construct DSA key from tuple.

190

191

Parameters:

192

- tup (tuple): (y, g, p, q) for public key or (y, g, p, q, x) for private key

193

- consistency_check (bool): Verify mathematical consistency

194

195

Returns:

196

DsaKey object

197

"""

198

199

def import_key(extern_key, passphrase=None):

200

"""

201

Import DSA key from external format.

202

203

Parameters:

204

- extern_key (bytes): Key in PEM, DER, or PKCS#8 format

205

- passphrase (bytes): Password for encrypted keys

206

207

Returns:

208

DsaKey object

209

"""

210

211

class DsaKey:

212

"""DSA key object for digital signatures."""

213

214

def has_private(self) -> bool:

215

"""Check if private key is present."""

216

217

def public_key(self):

218

"""Extract public key component."""

219

220

def export_key(self, **kwargs) -> bytes:

221

"""Export key in PEM, DER, or PKCS#8 format."""

222

223

# DSA parameters

224

y: int # Public key

225

g: int # Generator

226

p: int # Prime modulus

227

q: int # Prime divisor

228

x: int # Private key (private keys only)

229

```

230

231

### ElGamal

232

233

Public key algorithm based on discrete logarithm problem, primarily used for encryption with probabilistic properties.

234

235

```python { .api }

236

def generate(bits, randfunc):

237

"""

238

Generate ElGamal key pair.

239

240

Parameters:

241

- bits (int): Key size in bits

242

- randfunc (callable): Random function

243

244

Returns:

245

ElGamalKey object

246

"""

247

248

def construct(tup):

249

"""

250

Construct ElGamal key from tuple.

251

252

Parameters:

253

- tup (tuple): (p, g, y) for public key or (p, g, y, x) for private key

254

255

Returns:

256

ElGamalKey object

257

"""

258

259

class ElGamalKey:

260

"""ElGamal key object for encryption."""

261

262

def has_private(self) -> bool:

263

"""Check if private key is present."""

264

265

def public_key(self):

266

"""Extract public key component."""

267

268

# ElGamal parameters

269

p: int # Prime modulus

270

g: int # Generator

271

y: int # Public key

272

x: int # Private key (private keys only)

273

```

274

275

## Usage Examples

276

277

### RSA Key Operations

278

```python

279

from Crypto.PublicKey import RSA

280

from Crypto.Cipher import PKCS1_OAEP

281

282

# Generate RSA key pair

283

key = RSA.generate(2048)

284

public_key = key.publickey()

285

286

# Export keys

287

private_pem = key.export_key('PEM')

288

public_pem = public_key.export_key('PEM')

289

290

# Save encrypted private key

291

encrypted_key = key.export_key(

292

format='PEM',

293

passphrase='secret_password',

294

pkcs=8,

295

protection='PBKDF2WithHMAC-SHA1AndAES256-CBC'

296

)

297

298

# Import key from file

299

with open('private_key.pem', 'rb') as f:

300

imported_key = RSA.import_key(f.read(), passphrase='secret_password')

301

```

302

303

### ECC Key Operations

304

```python

305

from Crypto.PublicKey import ECC

306

307

# Generate ECC key with P-256 curve

308

key = ECC.generate(curve='P-256')

309

310

# Generate Ed25519 key for signatures

311

ed25519_key = ECC.generate(curve='Ed25519')

312

313

# Export public key in OpenSSH format

314

ssh_key = key.public_key().export_key(format='OpenSSH')

315

316

# Import from SEC1 format

317

with open('ec_key.pem', 'rb') as f:

318

imported_key = ECC.import_key(f.read())

319

```

320

321

### DSA Key Operations

322

```python

323

from Crypto.PublicKey import DSA

324

325

# Generate DSA key

326

key = DSA.generate(2048)

327

328

# Export in PKCS#8 format

329

pkcs8_key = key.export_key(format='PKCS8')

330

331

# Construct from components

332

reconstructed = DSA.construct((key.y, key.g, key.p, key.q, key.x))

333

```

334

335

## Key Format Support

336

337

### RSA Key Formats

338

- **PEM**: ASCII-armored format with headers

339

- **DER**: Binary ASN.1 encoding

340

- **PKCS#1**: RSA-specific format (RSAPrivateKey/RSAPublicKey)

341

- **PKCS#8**: Generic private key format

342

- **OpenSSH**: OpenSSH public key format

343

344

### ECC Key Formats

345

- **PEM/DER**: Standard ASN.1 formats

346

- **SEC1**: Elliptic curve private key format

347

- **PKCS#8**: Generic private key format

348

- **OpenSSH**: OpenSSH public key format (Ed25519/ECDSA)

349

350

### DSA Key Formats

351

- **PEM/DER**: Standard ASN.1 formats

352

- **PKCS#8**: Generic private key format

353

354

## Security Considerations

355

356

### Key Size Recommendations

357

- **RSA**: Minimum 2048 bits, prefer 3072+ for long-term security

358

- **ECC**: P-256 for most applications, P-384/P-521 for higher security

359

- **DSA**: 2048-bit L with 256-bit N for new applications

360

361

### Best Practices

362

- Use cryptographically secure random number generation

363

- Protect private keys with strong passphrases

364

- Prefer ECC over RSA for new applications (better performance/security ratio)

365

- Use appropriate padding schemes (OAEP for RSA encryption, PSS for signatures)

366

- Implement proper key lifecycle management

367

368

## Common Key Object Interface

369

370

```python { .api }

371

class KeyObjectInterface:

372

"""Common interface for all key objects."""

373

374

def has_private(self) -> bool:

375

"""Check if private key component is present."""

376

377

def public_key(self):

378

"""Extract public key component."""

379

380

def export_key(self, **kwargs) -> bytes:

381

"""Export key in specified format."""

382

383

def size_in_bits(self) -> int:

384

"""Key size in bits."""

385

```

386

387

## Error Handling

388

389

- `ValueError`: Invalid key parameters, unsupported formats, or mathematical inconsistencies

390

- `TypeError`: Incorrect parameter types

391

- `UnsupportedEccFeature`: ECC-specific unsupported operations

392

- `ImportError`: Missing dependencies for specific curves or formats