PGPy API¶
Exceptions¶
PGPEncryptionError
¶
-
exception
pgpy.errors.
PGPEncryptionError
¶ Raised when encryption fails
PGPDecryptionError
¶
-
exception
pgpy.errors.
PGPDecryptionError
¶ Raised when decryption fails
PGPOpenSSLCipherNotSupportedError
¶
-
exception
pgpy.errors.
PGPOpenSSLCipherNotSupportedError
¶ Raised when OpenSSL does not support the requested cipher
PGPInsecureCipherError
¶
-
exception
pgpy.errors.
PGPInsecureCipherError
¶ Raised when a cipher known to be insecure is attempted to be used to encrypt data
WontImplementError
¶
-
exception
pgpy.errors.
WontImplementError
¶ Raised when something that is not implemented, will not be implemented
Constants¶
PubKeyAlgorithm
¶
-
class
pgpy.constants.
PubKeyAlgorithm
(value)¶ Supported public key algorithms.
-
RSAEncryptOrSign
¶ Signifies that a key is an RSA key.
-
DSA
¶ Signifies that a key is a DSA key.
-
ElGamal
¶ Signifies that a key is an ElGamal key.
-
ECDH
¶ Signifies that a key is an ECDH key.
-
ECDSA
¶ Signifies that a key is an ECDSA key.
-
EllipticCurveOID
¶
-
class
pgpy.constants.
EllipticCurveOID
(value)¶ OIDs for supported elliptic curves.
-
Curve25519
¶ DJB’s fast elliptic curve
-
Ed25519
¶ Twisted Edwards variant of Curve25519
-
NIST_P256
¶ NIST P-256, also known as SECG curve secp256r1
-
NIST_P384
¶ NIST P-384, also known as SECG curve secp384r1
-
NIST_P521
¶ NIST P-521, also known as SECG curve secp521r1
-
Brainpool_P256
¶ Brainpool Standard Curve, 256-bit
Note
Requires OpenSSL >= 1.0.2
-
Brainpool_P384
¶ Brainpool Standard Curve, 384-bit
Note
Requires OpenSSL >= 1.0.2
-
Brainpool_P512
¶ Brainpool Standard Curve, 512-bit
Note
Requires OpenSSL >= 1.0.2
-
SECP256K1
¶ SECG curve secp256k1
-
SymmetricKeyAlgorithm
¶
-
class
pgpy.constants.
SymmetricKeyAlgorithm
(value)¶ Supported symmetric key algorithms.
-
IDEA
¶ Warning
IDEA is insecure. PGPy only allows it to be used for decryption, not encryption!
-
TripleDES
¶ Triple-DES with 168-bit key derived from 192
-
CAST5
¶ CAST5 (or CAST-128) with 128-bit key
-
Blowfish
¶ Blowfish with 128-bit key and 16 rounds
-
AES128
¶ AES with 128-bit key
-
AES192
¶ AES with 192-bit key
-
AES256
¶ AES with 256-bit key
-
Camellia128
¶ Camellia with 128-bit key
-
Camellia192
¶ Camellia with 192-bit key
-
Camellia256
¶ Camellia with 256-bit key
-
SignatureType
¶
-
class
pgpy.constants.
SignatureType
(value)¶ Types of signatures that can be found in a Signature packet.
-
BinaryDocument
¶ The signer either owns this document, created it, or certifies that it has not been modified.
-
CanonicalDocument
¶ The signer either owns this document, created it, or certifies that it has not been modified. The signature is calculated over the text data with its line endings converted to
<CR><LF>
.
-
Standalone
¶ This signature is a signature of only its own subpacket contents. It is calculated identically to a signature over a zero-length
BinaryDocument
.
-
Generic_Cert
¶ The issuer of this certification does not make any particular claim as to how well the certifier has checked that the owner of the key is in fact the person described by the User ID.
-
Persona_Cert
¶ The issuer of this certification has not done any verification of the claim that the owner of this key is the User ID specified.
-
Casual_Cert
¶ The issuer of this certification has done some casual verification of the claim of identity.
-
Positive_Cert
¶ The issuer of this certification has done substantial verification of the claim of identity.
-
Attestation
¶ This signature is issued by the primary key over itself and its user ID (or user attribute). See draft-ietf-openpgp-rfc4880bis-08
-
Subkey_Binding
¶ This signature is a statement by the top-level signing key that indicates that it owns the subkey. This signature is calculated directly on the primary key and subkey, and not on any User ID or other packets.
-
PrimaryKey_Binding
¶ This signature is a statement by a signing subkey, indicating that it is owned by the primary key and subkey. This signature is calculated the same way as a
Subkey_Binding
signature.
-
DirectlyOnKey
¶ A signature calculated directly on a key. It binds the information in the Signature subpackets to the key, and is appropriate to be used for subpackets that provide information about the key, such as the Revocation Key subpacket. It is also appropriate for statements that non-self certifiers want to make about the key itself, rather than the binding between a key and a name.
-
KeyRevocation
¶ A signature calculated directly on the key being revoked. Only revocation signatures by the key being revoked, or by an authorized revocation key, should be considered valid revocation signatures.
-
SubkeyRevocation
¶ A signature calculated directly on the subkey being revoked. Only revocation signatures by the top-level signature key that is bound to this subkey, or by an authorized revocation key, should be considered valid revocation signatures.
-
CertRevocation
¶ This signature revokes an earlier User ID certification signature or direct-key signature. It should be issued by the same key that issued the revoked signature or an authorized revocation key. The signature is computed over the same data as the certificate that it revokes.
-
Timestamp
¶ This signature is only meaningful for the timestamp contained in it.
-
ThirdParty_Confirmation
¶ This signature is a signature over some other OpenPGP Signature packet(s). It is analogous to a notary seal on the signed data.
-
KeyFlags
¶
-
class
pgpy.constants.
KeyFlags
(value)¶ Flags that determine a key’s capabilities.
-
Certify
¶ Signifies that a key may be used to certify keys and user ids. Primary keys always have this, even if it is not specified.
-
Sign
¶ Signifies that a key may be used to sign messages and documents.
-
EncryptCommunications
¶ Signifies that a key may be used to encrypt messages.
-
EncryptStorage
¶ Signifies that a key may be used to encrypt storage. Currently equivalent to
EncryptCommunications
.
-
Split
¶ Signifies that the private component of a given key may have been split by a secret-sharing mechanism. Split keys are not currently supported by PGPy.
-
Authentication
¶ Signifies that a key may be used for authentication.
-
MultiPerson
¶ Signifies that the private component of a key may be in the possession of more than one person.
-
RevocationReason
¶
-
class
pgpy.constants.
RevocationReason
(value)¶ Reasons explaining why a key or certificate was revoked.
-
NotSpecified
¶ No reason was specified. This is the default reason.
-
Superseded
¶ The key was superseded by a new key. Only meaningful when revoking a key.
-
Compromised
¶ Key material has been compromised. Only meaningful when revoking a key.
-
Retired
¶ Key is retired and no longer used. Only meaningful when revoking a key.
-
UserID
¶ User ID information is no longer valid. Only meaningful when revoking a certification of a user id.
-
Classes¶
PGPKey
¶
-
class
pgpy.
PGPKey
¶ PGPKey objects represent OpenPGP compliant keys along with all of their associated data.
PGPKey implements the __str__ method, the output of which will be the key composition in OpenPGP-compliant ASCII-armored format.
PGPKey implements the __bytes__ method, the output of which will be the key composition in OpenPGP-compliant binary format.
Any signatures within the PGPKey that are marked as being non-exportable will not be included in the output of either of those methods.
-
ascii_headers
¶ An
OrderedDict
of headers that appear, in order, in the ASCII-armored form of this object.
-
classmethod
from_file
(filename)¶ Create a new
PGPKey
object, with contents loaded from a file. May be binary or ASCII armored.Parameters: filename ( str
) – The path to the file to load.Raises: ValueError
if a properly formed PGP block was not found in the file atfilename
Raises: PGPError
if de-armoring or parsing failedReturns: A two element tuple
ofPGPKey
,OrderedDict
. TheOrderedDict
has the following format:key, others = PGPKey.from_file('path/to/keyfile') # others: { (Fingerprint, bool(key.is_public)): PGPKey }
-
classmethod
from_blob
(blob)¶ Create a new
PGPKey
object, with contents loaded from a blob. May be binary or ASCII armored.Parameters: blob ( str
,bytes
,unicode
,bytearray
) – The data to load.Raises: TypeError
if blob is not in the expected types aboveRaises: ValueError
if a properly formed PGP block was not found inblob
Raises: PGPError
if de-armoring or parsing failedReturns: A two element tuple
ofPGPKey
,OrderedDict
. TheOrderedDict
has the following format:key, others = PGPKey.from_file('path/to/keyfile') # others: { (Fingerprint, bool(key.is_public)): PGPKey }
-
property
created
¶ A
datetime
object of the creation date and time of the key, in UTC.
-
property
expires_at
¶ A
datetime
object of when this key is to be considered expired, if any. Otherwise,None
-
property
fingerprint
¶ The fingerprint of this key, as a
Fingerprint
object.
-
property
is_expired
¶ True
if this key is expired, otherwiseFalse
-
property
is_primary
¶ True
if this is a primary key;False
if this is a subkey
-
property
is_protected
¶ True
if this is a private key that is protected with a passphrase, otherwiseFalse
-
property
is_public
¶ True
if this is a public key, otherwiseFalse
-
property
is_unlocked
¶ False
if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwiseTrue
-
property
key_algorithm
¶ The
constants.PubKeyAlgorithm
pertaining to this key
-
property
key_size
¶ The size pertaining to this key.
int
for non-EC key algorithms;constants.EllipticCurveOID
for EC keys.New in version 0.4.1.
-
property
magic
¶ The magic string identifier for the current PGP type
-
property
pubkey
¶ If the
PGPKey
object is a private key, this method returns a corresponding public key object with all the trimmings. If it is already a public key, just return it.
-
property
signers
¶ A
set
of key ids of keys that were used to sign this key
-
property
subkeys
¶ An
OrderedDict
of subkeys bound to this primary key, if applicable, selected by 16-character keyid.
-
property
userattributes
¶ A
list
ofPGPUID
objects containing one or more images associated with this key
-
property
revocation_keys
¶ A
generator
with the list of keys that can revoke this key.See also
PGPSignature.revocation_key()
-
classmethod
new
(key_algorithm, key_size, created=None)¶ Generate a new PGP key
Parameters: - key_algorithm (
PubKeyAlgorithm
) – Key algorithm to use. - key_size (
int
orEllipticCurveOID
) – Key size in bits, unless key_algorithm isECDSA
orECDH
, in which case it should be the Curve OID to use. - created (
datetime
orNone
) – When was the key created? (None
or unset means now)
Returns: A newly generated
PGPKey
- key_algorithm (
-
protect
(passphrase, enc_alg, hash_alg)¶ Add a passphrase to a private key. If the key is already passphrase protected, it should be unlocked before a new passphrase can be specified.
Has no effect on public keys.
Parameters: - passphrase (
str
,unicode
) – A passphrase to protect the key with - enc_alg (
SymmetricKeyAlgorithm
) – Symmetric encryption algorithm to use to protect the key - hash_alg (
HashAlgorithm
) – Hash algorithm to use in the String-to-Key specifier
- passphrase (
-
unlock
(passphrase)¶ Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both private and passphrase-protected.
When the context managed block is exited, the unprotected private key material is removed.
Example:
privkey = PGPKey() privkey.parse(keytext) assert privkey.is_protected assert privkey.is_unlocked is False # privkey.sign("some text") <- this would raise an exception with privkey.unlock("TheCorrectPassphrase"): # privkey is now unlocked assert privkey.is_unlocked # so you can do things with it sig = privkey.sign("some text") # privkey is no longer unlocked assert privkey.is_unlocked is False
Emits a
UserWarning
if the key is public or not passphrase protected.Parameters: passphrase ( str
) – The passphrase to be used to unlock this key.Raises: PGPDecryptionError
if the passphrase is incorrect
-
add_uid
(uid, selfsign=True, **prefs)¶ Add a User ID to this key.
Parameters: - uid (
PGPUID
) – The user id to add - selfsign (
bool
) – Whether or not to self-sign the user id before adding it
Valid optional keyword arguments are identical to those of self-signatures for
PGPKey.certify()
. Any such keyword arguments are ignored if selfsign isFalse
- uid (
-
get_uid
(search)¶ Find and return a User ID that matches the search string given.
Parameters: search ( str
,unicode
) – A text string to match name, comment, or email address againstReturns: The first matching PGPUID
, orNone
if no matches were found.
-
del_uid
(search)¶ Find and remove a user id that matches the search string given. This method does not modify the corresponding
PGPUID
object; it only removes it from the list of user ids on the key.Parameters: search ( str
,unicode
) – A text string to match name, comment, or email address against
-
add_subkey
(key, **prefs)¶ Add a key as a subkey to this key.
Parameters: Other valid optional keyword arguments are identical to those of self-signatures for
PGPKey.certify()
-
sign
(subject, **prefs)¶ Sign text, a message, or a timestamp using this key.
Parameters: subject ( str
,PGPMessage
,None
) – The text to be signedRaises: PGPError
if the key is passphrase-protected and has not been unlockedRaises: PGPError
if the key is publicReturns: PGPSignature
The following optional keyword arguments can be used with
PGPKey.sign()
, as well asPGPKey.certify()
,PGPKey.revoke()
, andPGPKey.bind()
:Parameters: - expires (
datetime
,timedelta
) – Set an expiration date for this signature - notation (
dict
) – Add arbitrary notation data to this signature. - policy_uri (
str
) – Add a URI to the signature that should describe the policy under which the signature was issued. - revocable (
bool
) – IfFalse
, this signature will be marked non-revocable - user (
str
) – Specify which User ID to use when creating this signature. Also adds a “Signer’s User ID” to the signature. - created (
datetime
) – Specify the time that the signature should be made. If unset or None, it will use the present time. - intended_recipients (
list
) – Specify a list ofPGPKey
objects that will be encrypted to. - include_issuer_fingerprint (
bool
) – Whether to include a hashed subpacket indicating the issuer fingerprint. (only for v4 keys, defaults to True)
- expires (
-
certify
(subject, level=SignatureType.Generic_Cert, **prefs)¶ Sign a key or a user id within a key.
Parameters: - subject (
PGPKey
,PGPUID
) – The user id or key to be certified. - level –
Generic_Cert
,Persona_Cert
,Casual_Cert
, orPositive_Cert
. Only used if subject is aPGPUID
; otherwise, it is ignored.
Raises: PGPError
if the key is passphrase-protected and has not been unlockedRaises: PGPError
if the key is publicReturns: In addition to the optional keyword arguments accepted by
PGPKey.sign()
, the following optional keyword arguments can be used withPGPKey.certify()
.These optional keywords only make sense, and thus only have an effect, when self-signing a key or User ID:
Parameters: - usage (
set
) – Aset
of key usage flags, asKeyFlags
. This keyword is ignored for non-self-certifications. - ciphers (
list
) – A list of preferred symmetric ciphers, asSymmetricKeyAlgorithm
. This keyword is ignored for non-self-certifications. - hashes (
list
) – A list of preferred hash algorithms, asHashAlgorithm
. This keyword is ignored for non-self-certifications. - compression (
list
) – A list of preferred compression algorithms, asCompressionAlgorithm
. This keyword is ignored for non-self-certifications. - key_expiration (
datetime.datetime
,datetime.timedelta
) – Specify a key expiration date for when this key should expire, or atimedelta
of how long after the key was created it should expire. This keyword is ignored for non-self-certifications. - attested_certifications (
list
) – A list of third-party certifications, asPGPSignature
, that the certificate holder wants to attest to for redistribution with the certificate. Alternatively, any element in the list can be abytes
orbytearray
object of the appropriate length (the length of this certification’s digest). This keyword is only used for signatures of type Attestation. - keyserver (
str
,unicode
,bytes
) – Specify the URI of the preferred key server of the user. This keyword is ignored for non-self-certifications. - keyserver_flags (
set
) – A set of Key Server Preferences, asKeyServerPreferences
. - primary (
bool
) – Whether or not to consider the certified User ID as the primary one. This keyword is ignored for non-self-certifications, and any certifications directly on keys.
These optional keywords only make sense, and thus only have an effect, when signing another key or User ID:
Parameters: - trust (
tuple
of twoint
s) – Specify the level and amount of trust to assert when certifying a public key. Should be a tuple of twoint
s, specifying the trust level and trust amount. See RFC 4880 Section 5.2.3.13. Trust Signature for more on what these values mean. - regex (
str
) – Specify a regular expression to constrain the specified trust signature in the resulting signature. Symbolically signifies that the specified trust signature only applies to User IDs which match this regular expression. This is meaningless without also specifying trust level and amount. - exportable (
bool
) – Whether this certification is exportable or not.
- subject (
-
revoke
(target, **prefs)¶ Revoke a key, a subkey, or all current certification signatures of a User ID that were generated by this key so far.
Parameters: target ( PGPKey
,PGPUID
) – The key to revokeRaises: PGPError
if the key is passphrase-protected and has not been unlockedRaises: PGPError
if the key is publicReturns: PGPSignature
In addition to the optional keyword arguments accepted by
PGPKey.sign()
, the following optional keyword arguments can be used withPGPKey.revoke()
.Parameters: - reason (One of
constants.RevocationReason
.) – Defaults toconstants.RevocationReason.NotSpecified
- comment (
str
) – Defaults to an empty string.
- reason (One of
-
revoker
(revoker, **prefs)¶ Generate a signature that specifies another key as being valid for revoking this key.
Parameters: revoker ( PGPKey
) – ThePGPKey
to specify as a valid revocation key.Raises: PGPError
if the key is passphrase-protected and has not been unlockedRaises: PGPError
if the key is publicReturns: PGPSignature
In addition to the optional keyword arguments accepted by
PGPKey.sign()
, the following optional keyword arguments can be used withPGPKey.revoker()
.Parameters: sensitive ( bool
) – IfTrue
, this sets the sensitive flag on the RevocationKey subpacket. Currently, this has no other effect.
-
bind
(key, **prefs)¶ Bind a subkey to this key.
In addition to the optional keyword arguments accepted for self-signatures by
PGPkey.certify()
, the following optional keyword arguments can be used withPGPKey.bind()
.Parameters: crosssign ( bool
) – IfFalse
, do not attempt a cross-signature (defaults toTrue
). Subkeys which are not capable of signing will not produce a cross-signature in any case. Settingcrosssign
toFalse
is likely to produce subkeys that will be rejected by some other OpenPGP implementations.
-
verify
(subject, signature=None)¶ Verify a subject with a signature using this key.
Parameters: - subject (
str
,unicode
,None
,PGPMessage
,PGPKey
,PGPUID
) – The subject to verify - signature (
PGPSignature
) – If the signature is detached, it should be specified here.
Returns: - subject (
-
encrypt
(message, [sessionkey=None, ]**prefs)¶ Encrypt a PGPMessage using this key.
Parameters: - message (
PGPMessage
) – The message to encrypt. - sessionkey (
bytes
,str
) –Provide a session key to use when encrypting something. Default is
None
. IfNone
, a session key of the appropriate length will be generated randomly.Warning
Care should be taken when making use of this option! Session keys absolutely need to be unpredictable! Use the
gen_key()
method on the desiredSymmetricKeyAlgorithm
to generate the session key!
Raises: PGPEncryptionError
if encryption failed for any reason.Returns: A new
PGPMessage
with the encrypted contents ofmessage
The following optional keyword arguments can be used with
PGPKey.encrypt()
:Parameters: - cipher (
SymmetricKeyAlgorithm
) – Specifies the symmetric block cipher to use when encrypting the message. - user (
str
,unicode
) – Specifies the User ID to use as the recipient for this encryption operation, for the purposes of preference defaults and selection validation.
- message (
-
decrypt
(message)¶ Decrypt a PGPMessage using this key.
Parameters: message – An encrypted PGPMessage
Raises: PGPError
if the key is not private, or protected but not unlocked.Raises: PGPDecryptionError
if decryption fails for any other reason.Returns: A new PGPMessage
with the decrypted contents ofmessage
.
-
parse
(data)¶ this method is too abstract to understand
-
PGPKeyring
¶
-
class
pgpy.
PGPKeyring
¶ PGPKeyring objects represent in-memory keyrings that can contain any combination of supported private and public keys. It can not currently be conveniently exported to a format that can be understood by GnuPG.
-
ascii_headers
¶ An
OrderedDict
of headers that appear, in order, in the ASCII-armored form of this object.
-
load
(*args)¶ Load all keys provided into this keyring object.
Parameters: *args ( list
,tuple
,str
,unicode
,bytes
,bytearray
) – Each arg inargs
can be any of the formats supported byPGPKey.from_file()
andPGPKey.from_blob()
or aPGPKey
instance, or alist
ortuple
of these.Returns: a set
containing the unique fingerprints of all of the keys that were loaded during this operation.
-
key
(identifier)¶ A context-manager method. Yields the first
PGPKey
object that matches the provided identifier.Parameters: identifier ( PGPMessage
,PGPSignature
,str
) – The identifier to use to select a loaded key.Raises: KeyError
if there is no loaded key that satisfies the identifier.
-
fingerprints
(keyhalf='any', keytype='any')¶ List loaded fingerprints with some optional filtering.
Parameters: - keyhalf (
str
) – Can be ‘any’, ‘public’, or ‘private’. If ‘public’, or ‘private’, the fingerprints of keys of the the other type will not be included in the results. - keytype (
str
) – Can be ‘any’, ‘primary’, or ‘sub’. If ‘primary’ or ‘sub’, the fingerprints of keys of the the other type will not be included in the results.
Returns: a
set
of fingerprints of keys matching the filters specified.- keyhalf (
-
unload
(key)¶ Unload a loaded key and its subkeys.
Parameters: key ( PGPKey
) – The key to unload.The easiest way to do this is to select a key using
PGPKeyring.key()
first:with keyring.key("DSA von TestKey") as key: keyring.unload(key)
-
PGPMessage
¶
-
class
pgpy.
PGPMessage
¶ PGPMessage objects represent OpenPGP message compositions.
PGPMessage implements the
__str__
method, the output of which will be the message composition in OpenPGP-compliant ASCII-armored format.PGPMessage implements the
__bytes__
method, the output of which will be the message composition in OpenPGP-compliant binary format.Any signatures within the PGPMessage that are marked as being non-exportable will not be included in the output of either of those methods.
-
ascii_headers
¶ An
OrderedDict
of headers that appear, in order, in the ASCII-armored form of this object.
-
classmethod
from_file
(filename)¶ Create a new
PGPMessage
object, with contents loaded from a file. May be binary or ASCII armored.Parameters: filename ( str
) – The path to the file to load.Raises: ValueError
if a properly formed PGP block was not found in the file atfilename
Raises: PGPError
if de-armoring or parsing failedReturns: PGPMessage
-
classmethod
from_blob
(blob)¶ Create a new
PGPMessage
object, with contents loaded from a blob. May be binary or ASCII armored.Parameters: blob ( str
,bytes
,unicode
,bytearray
) – The data to load.Raises: TypeError
if blob is not in the expected types aboveRaises: ValueError
if a properly formed PGP block was not found inblob
Raises: PGPError
if de-armoring or parsing failedReturns: PGPMessage
-
property
encrypters
¶ A
set
containing all key ids (if any) to which this message was encrypted.
-
property
filename
¶ If applicable, returns the original filename of the message. Otherwise, returns an empty string.
-
property
is_compressed
¶ True
if this message will be compressed when exported
-
property
is_encrypted
¶ True
if this message is encrypted; otherwise,False
-
property
is_sensitive
¶ True
if this message is marked sensitive; otherwiseFalse
-
property
is_signed
¶ True
if this message is signed; otherwise,False
. Should always beFalse
if the message is encrypted.
-
property
issuers
¶ A
set
containing all key ids (if any) which have signed or encrypted this message.
-
property
magic
¶ The magic string identifier for the current PGP type
-
property
message
¶ The message contents
-
property
signatures
¶ A
set
containing all key ids (if any) which have signed this message.
-
property
signers
¶ A
set
containing all key ids (if any) which have signed this message.
-
classmethod
new
(message, **kwargs)¶ Create a new PGPMessage object.
Parameters: message ( str
,unicode
,bytes
,bytearray
) – The message to be stored.Returns: PGPMessage
The following optional keyword arguments can be used with
PGPMessage.new()
:Parameters: - file (
bool
) – if True,message
should be a path to a file. The contents of that file will be read and used as the contents of the message. - cleartext (
bool
) – if True, the message will be cleartext with inline signatures. - sensitive (
bool
) – if True, the filename will be set to ‘_CONSOLE’ to signal other OpenPGP clients to treat this message as being ‘for your eyes only’. Ignored if cleartext is True. - format (
str
) – Set the message format identifier. Ignored if cleartext is True. - compression – Set the compression algorithm for the new message.
Defaults to
CompressionAlgorithm.ZIP
. Ignored if cleartext is True. - encoding (
str
representing a valid codec in codecs) – Set the Charset header for the message.
- file (
-
encrypt
(passphrase, [sessionkey=None, ]**prefs)¶ Encrypt the contents of this message using a passphrase.
Parameters: - passphrase (
str
,unicode
,bytes
) – The passphrase to use for encrypting this message. - sessionkey (
bytes
,str
) –Provide a session key to use when encrypting something. Default is
None
. IfNone
, a session key of the appropriate length will be generated randomly.Warning
Care should be taken when making use of this option! Session keys absolutely need to be unpredictable! Use the
gen_key()
method on the desiredSymmetricKeyAlgorithm
to generate the session key!
Raises: Returns: A new
PGPMessage
containing the encrypted contents of this message.- passphrase (
-
decrypt
(passphrase)¶ Attempt to decrypt this message using a passphrase.
Parameters: passphrase ( str
,unicode
,bytes
) – The passphrase to use to attempt to decrypt this message.Raises: PGPDecryptionError
if decryption failed for any reason.Returns: A new PGPMessage
containing the decrypted contents of this message
-
parse
(packet)¶ this method is too abstract to understand
-
PGPSignature
¶
-
class
pgpy.
PGPSignature
¶ PGPSignature objects represent OpenPGP compliant signatures.
PGPSignature implements the
__str__
method, the output of which will be the signature object in OpenPGP-compliant ASCII-armored format.PGPSignature implements the
__bytes__
method, the output of which will be the signature object in OpenPGP-compliant binary format.-
ascii_headers
¶ An
OrderedDict
of headers that appear, in order, in the ASCII-armored form of this object.
-
classmethod
from_file
(filename)¶ Create a new
PGPSignature
object, with contents loaded from a file. May be binary or ASCII armored.Parameters: filename ( str
) – The path to the file to load.Raises: ValueError
if a properly formed PGP block was not found in the file atfilename
Raises: PGPError
if de-armoring or parsing failedReturns: PGPSignature
-
classmethod
from_blob
(blob)¶ Create a new
PGPSignature
object, with contents loaded from a blob. May be binary or ASCII armored.Parameters: blob ( str
,bytes
,unicode
,bytearray
) – The data to load.Raises: TypeError
if blob is not in the expected types aboveRaises: ValueError
if a properly formed PGP block was not found inblob
Raises: PGPError
if de-armoring or parsing failedReturns: PGPSignature
-
property
cipherprefs
¶ A
list
of preferred symmetric algorithms specified in this signature, if any. Otherwise, an emptylist
.
-
property
compprefs
¶ A
list
of preferred compression algorithms specified in this signature, if any. Otherwise, an emptylist
.
-
property
created
¶ A
datetime
of when this signature was created.
-
property
expires_at
¶ A
datetime
of when this signature expires, if a signature expiration date is specified. Otherwise,None
-
property
exportable
¶ False
if this signature is marked as being not exportable. Otherwise,True
.
-
property
features
¶ A
set
of implementation features specified in this signature, if any. Otherwise, an emptyset
.
-
property
hashprefs
¶ A
list
of preferred hash algorithms specified in this signature, if any. Otherwise, an emptylist
.
-
property
hash_algorithm
¶ The
HashAlgorithm
used when computing this signature.
-
property
is_expired
¶ True
if the signature has an expiration date, and is expired. Otherwise,False
-
property
key_algorithm
¶ The
PubKeyAlgorithm
of the key that generated this signature.
-
property
keyserver
¶ The preferred key server specified in this signature, if any. Otherwise, an empty
str
.
-
property
keyserverprefs
¶ A
list
ofKeyServerPreferences
in this signature, if any. Otherwise, an emptylist
.
-
property
magic
¶ The magic string identifier for the current PGP type
-
property
notation
¶ A
dict
of notation data in this signature, if any. Otherwise, an emptydict
.
-
property
policy_uri
¶ The policy URI specified in this signature, if any. Otherwise, an empty
str
.
-
property
revocable
¶ False
if this signature is marked as being not revocable. Otherwise,True
.
-
property
attested_certifications
¶ Returns a set of all the hashes of attested certifications covered by this Attestation Key Signature.
Unhashed subpackets are ignored.
-
property
signer
¶ The 16-character Key ID of the key that generated this signature.
-
property
signer_fingerprint
¶ The fingerprint of the key that generated this signature, if it contained. Otherwise, an empty
str
.
-
property
intended_recipients
¶ Returns an iterator over all the primary key fingerprints marked as intended encrypted recipients for this signature.
-
property
type
¶ The
SignatureType
of this signature.
-
attests_to
(othersig)¶ returns True if this signature attests to othersig (acknolwedges it for redistribution)
-
parse
(packet)¶ this method is too abstract to understand
-
PGPUID
¶
-
class
pgpy.
PGPUID
¶ PGPUID objects represent User IDs and User Attributes for keys.
PGPUID implements the
__format__
method for User IDs, returning a string in the format ‘name (comment) <email>’, leaving out any comment or email fields that are not present.-
property
name
¶ If this is a User ID, the stored name. If this is not a User ID, this will be an empty string.
-
property
comment
¶ If this is a User ID, this will be the stored comment. If this is not a User ID, or there is no stored comment, this will be an empty string.,
-
property
email
¶ If this is a User ID, this will be the stored email address. If this is not a User ID, or there is no stored email address, this will be an empty string.
-
property
userid
¶ If this is a User ID, this will be the full UTF-8 string. If this is not a User ID, this will be
None
.
-
property
image
¶ If this is a User Attribute, this will be the stored image. If this is not a User Attribute, this will be
None
.
-
property
is_primary
¶ If the most recent, valid self-signature specifies this as being primary, this will be True. Otherwise, False.
-
property
is_uid
¶ True
if this is a User ID, otherwise False.
-
property
is_ua
¶ True
if this is a User Attribute, otherwise False.
-
property
selfsig
¶ This will be the most recent, self-signature of this User ID or Attribute. If there isn’t one, this will be
None
.
-
property
signers
¶ This will be a set of all of the key ids which have signed this User ID or Attribute.
-
property
third_party_certifications
¶ A generator returning all third-party certifications
-
attested_to
(certifications)¶ filter certifications, only returning those that have been attested to by the first party
-
property
attested_third_party_certifications
¶ A generator that provides a list of all third-party certifications attested to by the primary key.
-
classmethod
new
(pn, comment='', email='')¶ Create a new User ID or photo.
Parameters: - pn (
bytearray
,str
,unicode
) – User ID name, or photo. If this is abytearray
, it will be loaded as a photo. Otherwise, it will be used as the name field for a User ID. - comment (
str
,unicode
) – The comment field for a User ID. Ignored if this is a photo. - email (
str
,unicode
) – The email address field for a User ID. Ignored if this is a photo.
Returns: - pn (
-
property
Other Objects¶
These are objects that are returned during certain operations, but are probably not useful to instantiate directly.
SignatureVerification
¶
-
class
pgpy.types.
SignatureVerification
¶ Returned by
PGPKey.verify()
Can be compared directly as a boolean to determine whether or not the specified signature verified.
-
property
good_signatures
¶ A generator yielding namedtuples of all signatures that were successfully verified in the operation that returned this instance. The namedtuple has the following attributes:
sigsubj.issues
-SecurityIssues
of whether the signature verified successfully or not. Must be 0 for success.sigsubj.by
- thePGPKey
that was used in this verify operation.sigsubj.signature
- thePGPSignature
that was verified.sigsubj.subject
- the subject that was verified using the signature.
-
property
bad_signatures
¶ A generator yielding namedtuples of all signatures that were not verified in the operation that returned this instance. The namedtuple has the following attributes:
sigsubj.verified
-bool
of whether the signature verified successfully or not.sigsubj.by
- thePGPKey
that was used in this verify operation.sigsubj.signature
- thePGPSignature
that was verified.sigsubj.subject
- the subject that was verified using the signature.
-
property
Fingerprint
¶
-
class
pgpy.types.
Fingerprint
(content)¶ A subclass of
str
. Can be compared using == and != tostr
,unicode
, and otherFingerprint
instances.Primarily used as a key for internal dictionaries, so it ignores spaces when comparing and hashing