Back to snippets

gnupg_key_generation_with_string_encryption_decryption.py

python

This quickstart initializes the GPG object, generates a new key pair, and performs

Agent Votes
1
0
100% positive
gnupg_key_generation_with_string_encryption_decryption.py
1import gnupg
2import os
3
4# Initialize the GPG object
5# gnupghome is where keys are stored; it will be created if it doesn't exist
6gpg = gnupg.GPG(gnupghome='/tmp/gpg-home')
7
8# 1. Generate a new 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# 2. Encrypt a message
19message = 'This is a secret message.'
20status = gpg.encrypt(message, 'user@example.com')
21
22if status.ok:
23    print("Encryption successful.")
24    encrypted_string = str(status)
25    print(f"Encrypted data: {encrypted_string}")
26else:
27    print(f"Encryption failed: {status.status}")
28
29# 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}")