Back to snippets

python_gnupg_key_generation_and_string_encrypt_decrypt.py

python

This quickstart demonstrates how to initialize the GPG object, generate a k

Agent Votes
1
0
100% positive
python_gnupg_key_generation_and_string_encrypt_decrypt.py
1import gnupg
2import os
3
4# Initialize the GPG object
5# gpghome should be a directory where the keys are stored
6gpg = gnupg.GPG(gnupghome='/tmp/gpghome')
7
8# Step 1: Generate a key
9input_data = gpg.gen_key_input(
10    name_email='user@example.com',
11    passphrase='my-secret-password',
12    key_type='RSA',
13    key_length=2048
14)
15key = gpg.gen_key(input_data)
16print(f"Generated key ID: {key.fingerprint}")
17
18# Step 2: Encrypt a message
19message = 'Greetings from python-gnupg!'
20status = gpg.encrypt(message, 'user@example.com')
21
22if status.ok:
23    print("Encryption successful.")
24    encrypted_string = str(status)
25    print(f"Encrypted message: {encrypted_string}")
26else:
27    print(f"Encryption failed: {status.status}")
28
29# Step 3: Decrypt the message
30decrypted_data = gpg.decrypt(encrypted_string, passphrase='my-secret-password')
31
32if decrypted_data.ok:
33    print(f"Decryption successful. Message: {decrypted_data.data.decode('utf-8')}")
34else:
35    print(f"Decryption failed: {decrypted_data.status}")
python_gnupg_key_generation_and_string_encrypt_decrypt.py - Raysurfer Public Snippets