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

encryption-decryption.mddocs/

0

# Encryption and Decryption

1

2

Symmetric and asymmetric encryption/decryption operations supporting multiple data formats and comprehensive configuration options for secure data handling.

3

4

## Capabilities

5

6

### Data Encryption

7

8

Encrypt data using public key cryptography (asymmetric) or symmetric encryption with configurable algorithms and output formats.

9

10

```python { .api }

11

def encrypt(self, data, recipients, **kwargs):

12

"""

13

Encrypt data for specified recipients.

14

15

Parameters:

16

- data (str): Data to encrypt

17

- recipients (str|list): Recipient key IDs, fingerprints, or email addresses

18

- **kwargs: Keyword arguments passed to encrypt_file() including:

19

- sign (str): Key ID to sign with (creates encrypted and signed message)

20

- always_trust (bool): Skip key validation

21

- passphrase (str): Passphrase for signing key

22

- armor (bool): ASCII-armor the output (default: True)

23

- symmetric (bool): Use symmetric encryption only

24

- extra_args (list): Additional GPG arguments

25

26

Returns:

27

Crypt: Result object with encrypted data and status

28

"""

29

30

def encrypt_file(self, fileobj_or_path, recipients, sign=None,

31

always_trust=False, passphrase=None, armor=True,

32

output=None, symmetric=False, extra_args=None):

33

"""

34

Encrypt a file or file-like object.

35

36

Parameters:

37

- fileobj_or_path (str|file): File path or file-like object to encrypt

38

- recipients (str|list): Recipient identifiers

39

- sign (str): Key ID for signing

40

- always_trust (bool): Skip key validation

41

- passphrase (str): Passphrase for signing or symmetric encryption

42

- armor (bool): ASCII-armor the output

43

- output (str): Output file path

44

- symmetric (bool): Use symmetric encryption

45

- extra_args (list): Additional GPG arguments

46

47

Returns:

48

Crypt: Result object with encryption status

49

"""

50

```

51

52

### Data Decryption

53

54

Decrypt data encrypted with GPG, supporting both asymmetric and symmetric decryption with comprehensive error handling.

55

56

```python { .api }

57

def decrypt(self, message, **kwargs):

58

"""

59

Decrypt GPG-encrypted data.

60

61

Parameters:

62

- message (str): Encrypted data to decrypt

63

- always_trust (bool): Skip key validation

64

- passphrase (str): Passphrase for decryption

65

- extra_args (list): Additional GPG arguments

66

67

Returns:

68

Crypt: Result object with decrypted data and verification info

69

"""

70

71

def decrypt_file(self, fileobj_or_path, always_trust=False,

72

passphrase=None, output=None, extra_args=None):

73

"""

74

Decrypt an encrypted file or file-like object.

75

76

Parameters:

77

- fileobj_or_path (str|file): File path or file-like object to decrypt

78

- always_trust (bool): Skip key validation

79

- passphrase (str): Passphrase for decryption

80

- output (str): Output file path for decrypted data

81

- extra_args (list): Additional GPG arguments

82

83

Returns:

84

Crypt: Result object with decryption status

85

"""

86

```

87

88

### Recipient Analysis

89

90

Analyze encrypted messages to determine recipient information without decrypting the content.

91

92

```python { .api }

93

def get_recipients(self, message, **kwargs):

94

"""

95

Get recipient information from encrypted data.

96

97

Parameters:

98

- message (str): Encrypted data to analyze

99

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

100

101

Returns:

102

Crypt: Result with recipient information

103

"""

104

105

def get_recipients_file(self, fileobj_or_path, extra_args=None):

106

"""

107

Get recipient information from encrypted file.

108

109

Parameters:

110

- fileobj_or_path (str|file): Encrypted file to analyze

111

- extra_args (list): Additional GPG arguments

112

113

Returns:

114

Crypt: Result with recipient information

115

"""

116

```

117

118

## Result Types

119

120

```python { .api }

121

class Crypt(StatusHandler):

122

ok: bool # True if operation succeeded

123

status: str # Operation status message

124

stderr: str # Error output from GPG

125

data: str # Encrypted/decrypted data

126

127

# Verification information (for decrypt operations)

128

valid: bool # True if signature is valid (decrypt + verify)

129

fingerprint: str # Signer's fingerprint (if signed)

130

username: str # Signer's username (if signed)

131

trust_level: int # Trust level of signing key

132

trust_text: str # Human-readable trust level

133

signature_id: str # Signature ID

134

creation_date: str # Signature creation date

135

136

# Recipients information (for get_recipients operations)

137

recipients: list # List of recipient key information

138

```

139

140

## Usage Examples

141

142

### Basic Encryption and Decryption

143

144

```python

145

import gnupg

146

147

gpg = gnupg.GPG()

148

149

# Encrypt data for single recipient

150

plaintext = "This is sensitive information"

151

encrypted = gpg.encrypt(plaintext, recipients=['alice@example.com'])

152

153

if encrypted.ok:

154

print("Encryption successful")

155

print(str(encrypted)) # ASCII-armored encrypted data

156

else:

157

print(f"Encryption failed: {encrypted.status}")

158

159

# Decrypt the data

160

decrypted = gpg.decrypt(str(encrypted), passphrase='alice_passphrase')

161

162

if decrypted.ok:

163

print("Decryption successful")

164

print(str(decrypted)) # Original plaintext

165

else:

166

print(f"Decryption failed: {decrypted.status}")

167

```

168

169

### Multiple Recipients

170

171

```python

172

# Encrypt for multiple recipients

173

recipients = [

174

'alice@example.com',

175

'bob@example.com',

176

'DEADBEEFCAFEBABE12345678' # Key fingerprint

177

]

178

179

encrypted = gpg.encrypt(plaintext, recipients=recipients, armor=True)

180

181

# Any of the recipients can decrypt

182

decrypted_by_alice = gpg.decrypt(str(encrypted), passphrase='alice_pass')

183

decrypted_by_bob = gpg.decrypt(str(encrypted), passphrase='bob_pass')

184

```

185

186

### Symmetric Encryption

187

188

```python

189

# Encrypt with passphrase only (no public key needed)

190

encrypted = gpg.encrypt(

191

"Secret data",

192

recipients=None, # No recipients for symmetric

193

symmetric=True,

194

passphrase='shared_secret',

195

cipher_algo='AES256'

196

)

197

198

# Decrypt with the same passphrase

199

decrypted = gpg.decrypt(str(encrypted), passphrase='shared_secret')

200

```

201

202

### File Encryption

203

204

```python

205

# Encrypt a file

206

result = gpg.encrypt_file(

207

'/path/to/document.pdf',

208

recipients=['recipient@example.com'],

209

output='/path/to/document.pdf.gpg',

210

armor=False # Binary output

211

)

212

213

if result.ok:

214

print("File encrypted successfully")

215

216

# Decrypt a file

217

result = gpg.decrypt_file(

218

'/path/to/document.pdf.gpg',

219

passphrase='recipient_passphrase',

220

output='/path/to/decrypted_document.pdf'

221

)

222

```

223

224

### Encryption with Signing

225

226

```python

227

# Encrypt and sign in one operation

228

encrypted_and_signed = gpg.encrypt(

229

"Important message",

230

recipients=['recipient@example.com'],

231

sign='sender@example.com', # Sign with this key

232

passphrase='sender_passphrase'

233

)

234

235

# Decrypt and verify signature

236

decrypted = gpg.decrypt(str(encrypted_and_signed),

237

passphrase='recipient_passphrase')

238

239

if decrypted.ok:

240

print(f"Decrypted: {str(decrypted)}")

241

if decrypted.valid:

242

print(f"Valid signature from: {decrypted.username}")

243

print(f"Fingerprint: {decrypted.fingerprint}")

244

print(f"Trust level: {decrypted.trust_text}")

245

else:

246

print("Invalid or no signature")

247

```

248

249

### Advanced Options

250

251

```python

252

# Encrypt with custom algorithms and compression

253

encrypted = gpg.encrypt(

254

"Data to encrypt",

255

recipients=['user@example.com'],

256

cipher_algo='AES256', # Strong encryption

257

digest_algo='SHA512', # Strong hash

258

compress_algo='BZIP2', # Better compression

259

extra_args=['--verbose'] # Additional GPG options

260

)

261

262

# Encrypt always trusting keys (skip validation)

263

encrypted = gpg.encrypt(

264

"Urgent message",

265

recipients=['new_key@example.com'],

266

always_trust=True # Skip key validation

267

)

268

```

269

270

### Recipient Analysis

271

272

```python

273

# Analyze encrypted message to see recipients

274

encrypted_data = """-----BEGIN PGP MESSAGE-----

275

...

276

-----END PGP MESSAGE-----"""

277

278

recipients_info = gpg.get_recipients(encrypted_data)

279

if recipients_info.ok:

280

print("Message encrypted for:")

281

for recipient in recipients_info.recipients:

282

print(f" - Key ID: {recipient}")

283

284

# Analyze encrypted file

285

recipients_info = gpg.get_recipients_file('/path/to/encrypted.gpg')

286

```

287

288

### Error Handling

289

290

```python

291

# Comprehensive error handling

292

def safe_encrypt(gpg_instance, data, recipients, **kwargs):

293

try:

294

result = gpg_instance.encrypt(data, recipients, **kwargs)

295

296

if result.ok:

297

return str(result)

298

else:

299

print(f"Encryption failed: {result.status}")

300

if result.stderr:

301

print(f"GPG stderr: {result.stderr}")

302

return None

303

304

except Exception as e:

305

print(f"Exception during encryption: {e}")

306

return None

307

308

# Safe decryption with retry logic

309

def safe_decrypt(gpg_instance, encrypted_data, passphrases):

310

for passphrase in passphrases:

311

try:

312

result = gpg_instance.decrypt(encrypted_data, passphrase=passphrase)

313

if result.ok:

314

return str(result)

315

except Exception as e:

316

print(f"Decryption attempt failed: {e}")

317

continue

318

319

print("All decryption attempts failed")

320

return None

321

```