or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

encryption-decryption.mdgpg-instance.mdindex.mdkey-discovery.mdkey-management.mdkeyserver-operations.mdsigning-verification.md

key-management.mddocs/

0

# Key Management

1

2

Comprehensive key management operations including generation, import, export, deletion, and keyring manipulation for maintaining cryptographic keys.

3

4

## Capabilities

5

6

### Key Generation

7

8

Generate new GPG key pairs with configurable parameters for cryptographic strength, expiration, and identity information.

9

10

```python { .api }

11

def gen_key(self, input):

12

"""

13

Generate a key pair using the provided input parameters.

14

15

Parameters:

16

- input (str): Key generation parameters (use gen_key_input() to create)

17

18

Returns:

19

GenKey: Result object with fingerprint and status information

20

"""

21

22

def gen_key_input(self, **kwargs):

23

"""

24

Generate input parameters for key generation.

25

26

Parameters:

27

- key_type (str): Key algorithm ('RSA', 'DSA', 'ECDSA', 'EDDSA')

28

- key_length (int): Key length in bits (1024, 2048, 4096)

29

- key_curve (str): Curve for ECC keys ('nistp256', 'nistp384', 'nistp521', 'brainpoolP256r1', etc.)

30

- subkey_type (str): Subkey algorithm

31

- subkey_length (int): Subkey length in bits

32

- subkey_curve (str): Subkey curve for ECC

33

- name_real (str): Real name for the key

34

- name_comment (str): Comment for the key

35

- name_email (str): Email address for the key

36

- expire_date (str): Expiration date ('0' for no expiration, 'YYYY-MM-DD', '2y', '6m', etc.)

37

- passphrase (str): Passphrase to protect the private key

38

- preferences (str): Algorithm preferences

39

- revoker (str): Designated revoker

40

- keyserver (str): Preferred keyserver

41

42

Returns:

43

str: Formatted input string for gen_key()

44

"""

45

46

def add_subkey(self, master_key, master_passphrase=None, algorithm='rsa',

47

usage='encrypt', expire='-'):

48

"""

49

Add a subkey to an existing master key.

50

51

Parameters:

52

- master_key (str): Master key fingerprint or ID

53

- master_passphrase (str): Passphrase for the master key

54

- algorithm (str): Subkey algorithm ('rsa', 'dsa', 'ecdsa', 'eddsa')

55

- usage (str): Key usage ('encrypt', 'sign', 'auth')

56

- expire (str): Expiration setting ('-' for same as master, '0' for no expiration)

57

58

Returns:

59

AddSubkey: Result object with subkey information

60

"""

61

```

62

63

### Key Import and Export

64

65

Import keys from various sources and export keys in different formats for sharing and backup purposes.

66

67

```python { .api }

68

def import_keys(self, key_data, extra_args=None, passphrase=None):

69

"""

70

Import key data into the keyring.

71

72

Parameters:

73

- key_data (str): ASCII-armored or binary key data

74

- extra_args (list): Additional GPG arguments

75

- passphrase (str): Passphrase for encrypted key data

76

77

Returns:

78

ImportResult: Result with import statistics and fingerprints

79

"""

80

81

def import_keys_file(self, key_path, **kwargs):

82

"""

83

Import keys from a file.

84

85

Parameters:

86

- key_path (str): Path to key file

87

- **kwargs: Additional arguments passed to import_keys()

88

89

Returns:

90

ImportResult: Result with import statistics

91

"""

92

93

def export_keys(self, keyids, secret=False, armor=True, minimal=False,

94

passphrase=None, expect_passphrase=True, output=None,

95

extra_args=None):

96

"""

97

Export keys from the keyring.

98

99

Parameters:

100

- keyids (str|list): Key IDs, fingerprints, or email addresses to export

101

- secret (bool): Export secret keys if True

102

- armor (bool): ASCII-armor the output

103

- minimal (bool): Export minimal key information

104

- passphrase (str): Passphrase for secret key export

105

- expect_passphrase (bool): Whether to expect passphrase prompt

106

- output (str): Output file path

107

- extra_args (list): Additional GPG arguments

108

109

Returns:

110

ExportResult: Result with exported key data

111

"""

112

```

113

114

### Key Discovery and Listing

115

116

Discover and list keys in keyrings with detailed information about key properties, signatures, and relationships.

117

118

```python { .api }

119

def list_keys(self, secret=False, keys=None, sigs=False):

120

"""

121

List keys in the keyring.

122

123

Parameters:

124

- secret (bool): List secret keys if True, public keys if False

125

- keys (list): Specific keys to list (default: all keys)

126

- sigs (bool): Include signature information

127

128

Returns:

129

ListKeys: List of key dictionaries with detailed information

130

"""

131

132

def scan_keys(self, filename):

133

"""

134

Scan keys from a file without importing them.

135

136

Parameters:

137

- filename (str): Path to key file to scan

138

139

Returns:

140

ScanKeys: List of key information without importing

141

"""

142

143

def scan_keys_mem(self, key_data):

144

"""

145

Scan keys from memory without importing them.

146

147

Parameters:

148

- key_data (str): Key data to scan

149

150

Returns:

151

ScanKeys: List of key information without importing

152

"""

153

```

154

155

### Key Deletion and Trust Management

156

157

Remove keys from keyrings and manage trust levels for web-of-trust operations.

158

159

```python { .api }

160

def delete_keys(self, fingerprints, secret=False, passphrase=None,

161

expect_passphrase=True, exclamation_mode=False):

162

"""

163

Delete keys from the keyring.

164

165

Parameters:

166

- fingerprints (str|list): Key fingerprints to delete

167

- secret (bool): Delete secret keys if True

168

- passphrase (str): Passphrase for secret key deletion

169

- expect_passphrase (bool): Whether to expect passphrase prompt

170

- exclamation_mode (bool): Force deletion without confirmation

171

172

Returns:

173

DeleteResult: Result with deletion status

174

"""

175

176

def trust_keys(self, fingerprints, trustlevel):

177

"""

178

Set trust level for keys in the web of trust.

179

180

Parameters:

181

- fingerprints (str|list): Key fingerprints to trust

182

- trustlevel (str): Trust level ('1'=unknown, '2'=never, '3'=marginal,

183

'4'=full, '5'=ultimate)

184

185

Returns:

186

TrustResult: Result with trust operation status

187

"""

188

```

189

190

## Result Types

191

192

```python { .api }

193

class GenKey(StatusHandler):

194

type: str # Generated key type

195

fingerprint: str # Generated key fingerprint

196

197

class AddSubkey(StatusHandler):

198

type: str # Subkey type

199

fingerprint: str # Subkey fingerprint

200

201

class ImportResult(StatusHandler):

202

count: int # Total keys processed

203

imported: int # Keys successfully imported

204

not_imported: int # Keys not imported

205

unchanged: int # Keys already in keyring

206

new_user_ids: int # New user IDs added

207

new_signatures: int # New signatures added

208

new_subkeys: int # New subkeys added

209

secret_imported: int # Secret keys imported

210

secret_unchanged: int # Secret keys unchanged

211

fingerprints: list # List of processed fingerprints

212

213

def summary(self):

214

"""Return human-readable import summary."""

215

216

class ExportResult(StatusHandler):

217

data: str # Exported key data

218

219

class DeleteResult(StatusHandler):

220

problem_reason: dict # Mapping of problem codes to descriptions

221

222

class TrustResult(StatusHandler):

223

pass

224

225

class ListKeys(list):

226

# List of key dictionaries containing:

227

# - type: Key type ('pub', 'sec', 'sub', 'ssb')

228

# - length: Key length in bits

229

# - algo: Algorithm number

230

# - keyid: Key ID

231

# - date: Creation date

232

# - expires: Expiration date

233

# - dummy: Dummy key indicator

234

# - ownertrust: Owner trust level

235

# - sig_class: Signature class

236

# - capabilities: Key capabilities

237

# - issuer: Key issuer

238

# - flag: Key flags

239

# - token: Token serial number

240

# - hash_algo: Hash algorithm

241

# - curve: Curve name for ECC keys

242

# - compliance_modes: Compliance mode flags

243

# - updated: Last updated timestamp

244

# - origin: Key origin

245

# - fingerprint: Key fingerprint

246

# - uids: List of user IDs

247

# - sigs: List of signatures (if requested)

248

# - subkeys: List of subkeys

249

250

class ScanKeys(ListKeys):

251

# Same structure as ListKeys but for scanned keys

252

pass

253

```

254

255

## Usage Examples

256

257

### Key Generation

258

259

```python

260

import gnupg

261

262

gpg = gnupg.GPG()

263

264

# Generate basic RSA key pair

265

input_data = gpg.gen_key_input(

266

key_type='RSA',

267

key_length=2048,

268

name_real='John Doe',

269

name_email='john@example.com',

270

expire_date='2y',

271

passphrase='secure_passphrase'

272

)

273

key = gpg.gen_key(input_data)

274

print(f"Generated key: {key.fingerprint}")

275

276

# Generate ECC key with custom parameters

277

input_data = gpg.gen_key_input(

278

key_type='ECDSA',

279

key_curve='nistp384',

280

subkey_type='ECDH',

281

subkey_curve='nistp384',

282

name_real='Jane Smith',

283

name_comment='Work Key',

284

name_email='jane@company.com',

285

expire_date='1y',

286

passphrase='work_passphrase'

287

)

288

key = gpg.gen_key(input_data)

289

```

290

291

### Key Import and Export

292

293

```python

294

# Import key from ASCII-armored data

295

key_data = """-----BEGIN PGP PUBLIC KEY BLOCK-----

296

...

297

-----END PGP PUBLIC KEY BLOCK-----"""

298

299

result = gpg.import_keys(key_data)

300

print(f"Imported {result.imported} keys")

301

print(f"Fingerprints: {result.fingerprints}")

302

303

# Import from file

304

result = gpg.import_keys_file('/path/to/keyfile.asc')

305

306

# Export public key

307

exported = gpg.export_keys('john@example.com')

308

print(exported.data)

309

310

# Export secret key with passphrase

311

exported = gpg.export_keys('john@example.com', secret=True,

312

passphrase='secure_passphrase')

313

314

# Export to file

315

gpg.export_keys(['key1@example.com', 'key2@example.com'],

316

output='/path/to/exported_keys.asc')

317

```

318

319

### Key Discovery

320

321

```python

322

# List all public keys

323

keys = gpg.list_keys()

324

for key in keys:

325

print(f"Key ID: {key['keyid']}")

326

print(f"Fingerprint: {key['fingerprint']}")

327

print(f"User IDs: {key['uids']}")

328

print(f"Length: {key['length']} bits")

329

330

# List secret keys

331

secret_keys = gpg.list_keys(secret=True)

332

333

# List specific keys with signatures

334

specific_keys = gpg.list_keys(keys=['john@example.com'], sigs=True)

335

336

# Scan keys from file without importing

337

scanned = gpg.scan_keys('/path/to/keyfile.asc')

338

for key in scanned:

339

print(f"Would import: {key['uids']}")

340

```

341

342

### Key Management

343

344

```python

345

# Delete public key

346

result = gpg.delete_keys('FINGERPRINT')

347

print(f"Deletion status: {result.status}")

348

349

# Delete secret key (requires confirmation)

350

result = gpg.delete_keys('FINGERPRINT', secret=True,

351

passphrase='secure_passphrase')

352

353

# Set trust level

354

result = gpg.trust_keys(['FINGERPRINT1', 'FINGERPRINT2'], '4') # Full trust

355

356

# Add subkey to existing key

357

result = gpg.add_subkey('MASTER_FINGERPRINT',

358

master_passphrase='master_pass',

359

algorithm='rsa',

360

usage='encrypt')

361

print(f"Added subkey: {result.fingerprint}")

362

```