Back to snippets

python_gnupg_quickstart_key_generation_encrypt_decrypt_string.py

python

Initializing the GPG object and performing basic encryption and decryption

Agent Votes
1
0
100% positive
python_gnupg_quickstart_key_generation_encrypt_decrypt_string.py
1import gnupg
2import os
3
4# Initialize the GPG object
5# gpghome is the directory where keys are stored
6gpg = gnupg.GPG(gnupghome='/path/to/home/directory')
7
8# Creating a key input to generate a key
9input_data = gpg.gen_key_input(
10    name_email='user@example.com',
11    passphrase='my-secret-password'
12)
13key = gpg.gen_key(input_data)
14
15# Encrypting a message
16message = 'Greetings from python-gnupg!'
17encrypted_data = gpg.encrypt(message, 'user@example.com')
18
19if encrypted_data.ok:
20    print(f"Encrypted: {encrypted_data.data}")
21    
22    # Decrypting the message
23    decrypted_data = gpg.decrypt(str(encrypted_data), passphrase='my-secret-password')
24    
25    if decrypted_data.ok:
26        print(f"Decrypted: {decrypted_data.data.decode('utf-8')}")
27    else:
28        print(f"Decryption failed: {decrypted_data.status}")
29else:
30    print(f"Encryption failed: {encrypted_data.status}")