Passphrase Protection
To protect a private key with a passphrase, use key.protect(passphrase, symmetric_algorithm, hash_algorithm). After this, key.is_protected will be True.
Unlocking Keys
To use a protected key, use the key.unlock(passphrase) context manager. This is the recommended way to handle secret material as it automatically removes the unprotected key material from the object once the block is exited. If the passphrase is incorrect, it raises a PGPDecryptionError.
import pgpy
from pgpy.constants import SymmetricKeyAlgorithm, HashAlgorithm
# Protecting a key
key.protect("C0rrectPassphr@se", SymmetricKeyAlgorithm.AES256, HashAlgorithm.SHA256)
# Unlocking a key using a context manager
with key.unlock("C0rrectPassphr@se"):
# key.is_unlocked is True inside this block
# Perform cryptographic operations here
pass
# key.is_unlocked is False once the block exits