PyGPGME API

Context

class gpgme.Context

Configuration and internal state for cryptographic operations.

This is the main class of gpgme. The constructor takes no arguments:

ctx = gpgme.Context()
card_edit(key, callback, out, /)
decrypt(cipher, plain, /)

Decrypts the ciphertext and writes out the plaintext.

To decrypt data, you must have one of the recipients’ private keys in your keyring (for public key encryption) or the passphrase (for symmetric encryption). If gpg finds the key but needs a passphrase to unlock it, the .passphrase_cb callback will be used to ask for it.

Parameters:
  • cipher (file) – A file-like object opened for reading, containing the encrypted data.

  • plain (file) – A file-like object opened for writing, where the decrypted data will be written.

See also decrypt_verify() and encrypt().

decrypt_verify(cipher, plain, /)

Decrypt ciphertext and verify signatures.

Like decrypt(), but also checks the signatures of the ciphertext.

Parameters:
  • cipher (file) – A file-like object opened for reading, containing the encrypted data.

  • plain (file) – A file-like object opened for writing, where the decrypted data will be written.

Returns:

A list of Signature instances (one for each key that was used in the signature). Note that you need to inspect the return value to check whether the signatures are valid – a syntactically correct but invalid signature does not raise an error!

Return type:

list[Signature]

See also encrypt_sign().

delete(key, flags=0, /)
edit(key, callback, out, /)
encrypt(recipients, flags, plaintext, ciphertext, /)

Encrypts plaintext so it can only be read by the given recipients.

Parameters:
  • recipients (list[Key]) – A list of Key objects. Only people in posession of the corresponding private key (for public key encryption) or passphrase (for symmetric encryption) will be able to decrypt the result.

  • flags (EncryptFlags) – See GPGME docs for details.

  • plaintext (file) – A file-like object opened for reading, containing the data to be encrypted.

  • ciphertext (file) – A file-like object opened for writing, where the encrypted data will be written.

See also encrypt_sign() and decrypt().

encrypt_sign(recipients, flags, plain, cipher, /)

Encrypt and sign plaintext.

Works like encrypt(), but the ciphertext is also signed using all keys listed in Context.signers.

Parameters:
  • recipients (list[Key]) – A list of Key objects. Only people in posession of the corresponding private key (for public key encryption) or passphrase (for symmetric encryption) will be able to decrypt the result.

  • flags (EncryptFlags) – See GPGME docs for details.

  • plaintext (file) – A file-like object opened for reading, containing the data to be encrypted.

  • ciphertext (file) – A file-like object opened for writing, where the encrypted data will be written.

Returns:

A list of NewSignature instances (one

for each key in Context.signers).

Return type:

list[NewSignature]

See also decrypt_verify().

export(pattern, keydata, export_mode=0, /)
export_keys(keys, keydata, export_mode=0, /)

Export the given list of keys.

genkey(params, pubkey=None, seckey=None, /)

Generate a new key pair.

The functionality of this method depends on the crypto backend set via Context.protocol. This documentation only covers PGP/GPG (i.e. Protocol.OpenPGP).

The generated key pair is automatically added to the key ring. Use set_engine_info() to configure the location of the key ring files.

Parameters:
  • params (str) –

    A string containing the parameters for key generation. The general syntax is as follows:

    <GnupgKeyParms format="internal">
      Key-Type: RSA
      Key-Length: 2048
      Name-Real: Jim Joe
      Passphrase: secret passphrase
      Expire-Date: 0
    </GnupgKeyParms>
    

    For a detailed listing of the available options please refer to the GPG key generation documentation.

  • public (file) – Must be None.

  • secret (file) – Must be None.

Returns:

An instance of gpgme.GenkeyResult.

Return type:

GenkeyResult

get_engine_info()
get_key(fingerprint, secret=False, /)

Finds a key with the given fingerprint (a string of hex digits) in the user’s keyring.

Parameters:
  • fingerprint (str) – Fingerprint of the key to look for

  • secret (bool) – If True, only private keys will be returned.

Returns:

the key matching the fingerprint.

Return type:

Key

If no key can be found, raises GpgmeError.

import_(keydata, /)
import_keys(keys, /)
keylist(pattern=None, secret=False, /)

Searches for keys matching the given pattern(s).

Parameters:
  • pattern (str | list[str] | None) – If None or not supplied, the KeyIter fetches all available keys. If a string, it fetches keys matching the given pattern (such as a name or email address). If a sequence of strings, it fetches keys matching at least one of the given patterns.

  • secret (bool) – If True, only secret keys will be returned (like ‘gpg -K’).

Returns:

an iterator over the matching Key objects.

Return type:

KeyIter

set_engine_info(protocol, file_name, home_dir, /)

Configure a crypto backend.

Updates the configuration of the crypto backend for the given protocol. If this function is used then it must be called before any crypto operation is performed on the context.

Parameters:
  • protocol (Protocol) – One of the :class:Protocol constants specifying which crypto backend is to be configured. Note that this does not change which crypto backend is actually used, see Context.protocol for that.

  • file_name (str) – The path to the executable implementing the protocol. If None then the default will be used.

  • home_dir (str) – The path of the configuration directory of the crypto backend. If None then the default will be used.

set_locale(category, value, /)
sign(plain, sig, sig_mode=0, /)

Sign plaintext to certify and timestamp it.

The plaintext is signed using all keys listed in Context.signers.

Parameters:
  • plain (file) – A file-like object opened for reading, containing the plaintext to be signed.

  • sig (file) – A file-like object opened for writing, where the signature data will be written. The signature data may contain the plaintext or not, see the mode parameter.

  • sig_mode (SigMode) – One of the :class:SigMode constants.

Returns:

A list of NewSignature instances (one

for each key in Context.signers).

Return type:

list[NewSignature]

verify(sig, signed_text, plaintext, /)

Verify signature(s) and extract plaintext.

Parameters:
  • sig (file) – a file-like object opened for reading, containing the signature data.

  • signed_text (file | None) – If sig contains a detached signature (i.e. created using SigMode.DETACHED) then signed_text should be a file-like object opened for reading containing the text covered by the signature.

  • plaintext (file | None) – If sig contains a normal or cleartext signature (i.e. created using SigMode.NORMAL or SigMode.CLEAR) then plaintext should be a file-like object opened for writing that will receive the extracted plaintext.

Returns:

A list of Signature instances (one for each

key that was used in sig). Note that you need to inspect the return value to check whether the signatures are valid – a syntactically correct but invalid signature does not raise an error!

Return type:

list[Signature]

armor

Whether encrypted data should be ASCII-armored or not.

Used by encrypt(), meth:encrypt_sign, and sign().

include_certs

How many certificates will be included in an S/MIME signed message.

See GPGME docs for details.

keylist_mode

Default key listing behaviour.

Controls which keys keylist() returns. The value is a bitwise OR combination of one or multiple of the KeylistMode constants. Defaults to KeylistMode.LOCAL.

offline

Whether GPG should operate in offline mode.

passphrase_cb

A callback that will get a passphrase from the user.

The callable must have the following signature:

callback(uidHint, passphraseInfo, prevWasBad, fd)

uidHint: a string describing the key whose passphrase is needed, or

None.

passphraseInfo: a string containing more information about the

required passphrase, or None.

prevWasBad: If the user gave a bad passphrase and we’re asking again,

this will be 1, otherwise 0.

fd: A numeric file-descriptor, as returned by os.open().

The callback is required to prompt the user for a passphrase, then write the passphrase followed by a ‘n’ to the file-descriptor fd using os.write(). If the user indicates they wish to cancel the operation, you should raise a gpgme.GpgmeError whose .code attribute is set to ERR_CANCELED.

pinentry_mode

Set to PINENTRY_MODE_* constant.

See GPGME docs for details.

progress_cb
protocol

The encryption system for this context (one of the Protocol constants).

sender

The sender address to include in signatures.

sig_notations

A tuple of notations added to signatures using the .sign() method.

signers

List of Key instances used for signing.

See also sign() and encrypt_sign().

textmode

Whether text mode is enabled.

GenkeyResult

class gpgme.GenkeyResult

Key generation result.

Instances of this class are usually obtained as the return value of Context.genkey().

fpr

String containing the fingerprint of the generated key.

If both a primary and a subkey were generated then this is the fingerprint of the primary key. For crypto backends that do not provide key fingerprints this is None.

primary

True if a primary key was generated.

sub

True if a subkey was generated.

Key

class gpgme.Key
can_authenticate

True if the key (i.e. one of its subkeys) can be used for authentication.

can_certify

True if the key (i.e. one of its subkeys) can be used to create key certificates.

can_encrypt

True if the key (i.e. one of its subkeys) can be used for encryption.

can_sign

True if the key (i.e. one of its subkeys) can be used to create signatures.

chain_id

If Key.protocol is Protocol.CMS then this is the chain ID, which can be used to built the certificate chain.

disabled

True if the key is disabled.

expired

True if the key has expired.

invalid

True if the key is invalid.

This might have several reasons. For example, for the S/MIME backend it will be set during key listing if the key could not be validated due to a missing certificates or unmatched policies.

issuer_name

If Key.protocol is Protocol.CMS then this is the issuer name.

issuer_serial

If Key.protocol is Protocol.CMS then this is the issuer serial.

keylist_mode

The keylist mode that was active when the key was retrieved.

See Context.keylist_mode.

owner_trust

If Key.protocol is Protocol.OpenPGP then this is the owner trust.

protocol

The protocol supported by this key. See the Protocol constants.

revoked

True if the key has been revoked.

secret

True if the key is a secret key.

Note that this will always be true even if the corresponding subkey flag may be false (offline/stub keys). This is only set if a listing of secret keys has been requested or if KeylistMode.WITH_SECRET is active.

subkeys

List of the key’s subkeys as instances of Subkey.

The first subkey in the list is the primary key and usually available.

uids

List of the key’s user IDs as instances of UserId.

The first user ID in the list is the main (or primary) user ID.

NewSignature

class gpgme.NewSignature

Data for newly created signatures.

Instances of this class are usually obtained as the result value of Context.sign() or Context.encrypt_sign().

fpr
hash_algo
pubkey_algo
sig_class
timestamp
type

Signature

class gpgme.Signature

Signature verification data.

Instances of this class are usually obtained as the return value of Context.verify() or Context.decrypt_verify().

exp_timestamp

Expiration timestamp of the signature, or 0 if the signature does not expire.

fpr

Fingerprint string

hash_algo

The hash algorithm of the signature, as a HashAlgo constant.

notations

A list of notation data represented by SigNotation objects.

pubkey_algo

The public key algorithm of the signature, as a PubkeyAlgo constant.

status

If an error occurred during verification (for example because the signature is not valid) then this attribute contains a corresponding GpgmeError instance. Otherwise it is None.

summary

A bit array encoded as an integer containing general information about about the signature.

Combine this value with one of the Sigsum constants using bitwise AND.

timestamp

Creation timestamp of the signature.

validity

Validity of the signature. See Signature.validity_reason.

validity_reason

If a signature is not valid this may provide a reason why. See Signature.validity.

wrong_key_usage

True if the key was not used according to its policy.

Helper Objects

Stuff that’s mostly used internally, but it’s good to know it’s there.

class gpgme.KeyIter

Iterable yielding Key instances for keylist results.

gpgme.gpgme_version

Version string of libgpgme used to build this module.

class gpgme.GpgmeError
class gpgme.ImportResult
class gpgme.KeySig
class gpgme.Subkey
class gpgme.UserId

Constants

Protocol Selection

The following constants can be used as value for Context.protocol. They are also returned via Key.protocol.

class gpgme.Protocol(enum.IntEnum)
OpenPGP = 0

This specifies the OpenPGP protocol.

CMS = 1

This specifies the Cryptographic Message Syntax.

ASSUAN = 3

Under development. Please ask on gnupg-devel@gnupg.org for help.

G13 = 4

Under development. Please ask on gnupg-devel@gnupg.org for help.

UISERVER = 5

Under development. Please ask on gnupg-devel@gnupg.org for help.

SPAWN = 6

Special protocol for use with gpgme_op_spawn.

UNKNOWN = 255

Reserved for future extension. You may use this to indicate that the used protocol is not known to the application. Currently, GPGME does not accept this value in any operation, though, except for gpgme_get_protocol_name.

Key Listing Mode

Bitwise OR combinations of the following constants can be used as values for Context.keylist_mode.

class gpgme.KeylistMode(enum.IntFlag)
LOCAL = 1

Specifies that the local keyring should be searched. This is the default.

EXTERN = 2

Specifies that an external source should be searched. The type of external source is dependant on the crypto engine used and whether it is combined with LOCAL. For example, it can be a remote keyserver or LDAP certificate server.

SIGS = 4

Specifies that the key signatures should be included in the listed keys.

SIG_NOTATIONS = 8

Specifies that the signature notations on key signatures should be included in the listed keys. This only works if SIGS is also enabled.

WITH_SECRET = 16

Returns information about the presence of a corresponding secret key in a public key listing. A public key listing with this mode is slower than a standard listing but can be used instead of a second run to list the secret keys. This is only supported for GnuPG versions >= 2.1.

EPHEMERAL = 128

Specifies that keys flagged as ephemeral are included in the listing.

VALIDATE = 256

Specifies that the backend should do key or certificate validation and not just get the validity information from an internal cache. This might be an expensive operation and is in general not useful. Currently only implemented for the S/MIME backend and ignored for other backends.

Encryption Flags

Bitwise OR combinations of the following constants can be used for the flags parameter of Context.encrypt() and Context.encrypt_sign().

class gpgme.EncryptFlags(enum.IntFlags)
ALWAYS_TRUST = 1

Specifies that all the recipients in recp should be trusted, even if the keys do not have a high enough validity in the keyring. This flag should be used with care; in general it is not a good idea to use any untrusted keys.

NO_ENCRYPT_TO = 2

Specifies that no default or hidden default recipients as configured in the crypto backend should be included. This can be useful for managing different user profiles.

PREPARE = 4

Used with the UI Server protocol to prepare an encryption.

EXPECT_SIGN = 8

Used with the UI Server protocol to advise the UI server to expect a sign command.

NO_COMPRESS = 16

Specifies that the plaintext shall not be compressed before it is encrypted. This is in some cases useful if the length of the encrypted message may reveal information about the plaintext.

Signing Modes

The following constants can be used for the mode parameter of Context.sign().

class gpgme.SigMode(enum.IntEnum)
NORMAL = 0

A normal signature is made, the output includes the plaintext and the signature. Context.armor is respected.

DETACH = 1

A detached signature is created. Context.armor is respected.

CLEAR = 2

A cleartext signature is created. Context.armor is ignored.

Signature Verification

The following bit masks can be used to extract individual bits from Signature.summary using bitwise AND.

class gpgme.Sigsum(enum.IntFlag)
VALID = 1

The signature is fully valid.

GREEN = 2

The signature is good but one might want to display some extra information. Check the other bits.

RED = 4

The signature is bad. It might be useful to check other bits and display more information, i.e. a revoked certificate might not render a signature invalid when the message was received prior to the cause for the revocation.

KEY_REVOKED = 16

The key or at least one certificate has been revoked.

KEY_EXPIRED = 32

The key or one of the certificates has expired.

SIG_EXPIRED = 64

The signature has expired.

KEY_MISSING = 128

Can’t verify due to a missing key or certificate.

CRL_MISSING = 256

The certificate revocation list (or an equivalent mechanism) is not available.

CRL_TOO_OLD = 512

The available certificate revocation list is too old.

BAD_POLICY = 1024

A policy requirement was not met.

SYS_ERROR = 2048

A system error occured.