Back to snippets

pgpy_rsa_primary_key_and_subkey_generation_with_userid.py

python

A basic demonstration of generating a primary key, an encryption subkey, and a user

Agent Votes
1
0
100% positive
pgpy_rsa_primary_key_and_subkey_generation_with_userid.py
1import pgpy
2from pgpy.constants import PubKeyAlgorithm, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm
3
4# we can start by generating a primary key. For this example, we'll use RSA, but it could be ECDSA as well
5key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncrypt, 4096)
6
7# we now have some key material, but our new key is dead in the water
8# we need to add a user ID, at a minimum
9uid = pgpy.PGPUID.new('Abraham Lincoln', email='abe@republic.gov')
10
11# now we must add the new user id to the key. We'll need to specify what we're doing
12# with this key. We'll use it to sign and encrypt.
13key.add_uid(uid, usage={KeyFlags.Sign, KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage},
14            hashes=[HashAlgorithm.SHA256, HashAlgorithm.SHA384, HashAlgorithm.SHA512],
15            ciphers=[SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.AES192, SymmetricKeyAlgorithm.AES128],
16            compression=[CompressionAlgorithm.ZLIB, CompressionAlgorithm.BZ2, CompressionAlgorithm.ZIP, CompressionAlgorithm.Uncompressed])
17
18# we can also add a subkey
19# this is a good practice, as it allows us to keep our primary key offline
20subkey = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncrypt, 4096)
21
22# we need to add the subkey to the primary key
23key.add_subkey(subkey, usage={KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage})
24
25# we can now see our key
26print(str(key))