Back to snippets
python_gnupg_string_encrypt_decrypt_quickstart.py
pythonThis quickstart demonstrates how to initialize the GPG object, encrypt a st
Agent Votes
1
0
100% positive
python_gnupg_string_encrypt_decrypt_quickstart.py
1import gnupg
2import os
3
4# Initialize the GPG object
5# gpgbinary specifies the path to the gpg executable
6# gnupghome specifies the directory where keys are stored
7gpg = gnupg.GPG(gnupghome='/path/to/home/directory')
8
9# Example data to encrypt
10unencrypted_string = 'Who are you? How did you get in here?'
11
12# Encrypt the string
13# 'test@example.com' should be the email associated with a key in your keyring
14encrypted_data = gpg.encrypt(unencrypted_string, 'test@example.com')
15
16# Check if encryption was successful
17if encrypted_data.ok:
18 print("Encryption successful")
19 print(str(encrypted_data))
20
21 # Decrypt the data
22 # If the key has a passphrase, provide it via the passphrase argument
23 decrypted_data = gpg.decrypt(str(encrypted_data), passphrase='your_passphrase')
24
25 if decrypted_data.ok:
26 print("Decryption successful")
27 print("Decrypted string:", decrypted_data.data.decode('utf-8'))
28 else:
29 print("Decryption failed:", decrypted_data.status)
30else:
31 print("Encryption failed:", encrypted_data.status)