gnupg package¶
gnupg module¶
This module contains public classes for working with GnuPG. To get started, do:
>>> import gnupg
>>> gpg = gnupg.GPG()
- class GPG(binary=None, homedir=None, verbose=False, use_agent=False, keyring=None, secring=None, ignore_homedir_permissions=False, options=None)¶
Bases: gnupg._meta.GPGBase
Python interface for handling interactions with GnuPG, including keyfile generation, keyring maintainance, import and export, encryption and decryption, sending to and recieving from keyservers, and signing and verification.
Initialize a GnuPG process wrapper.
Parameters: - binary (str) – Name for GnuPG binary executable. If the absolute path is not given, the environment variable $PATH is searched for the executable and checked that the real uid/gid of the user has sufficient permissions.
- homedir (str) – Full pathname to directory containing the public and private keyrings. Default is whatever GnuPG defaults to.
- ignore_homedir_permissions (bool) – If true, bypass check that homedir be writable.
- verbose (str or int or bool) – String or numeric value to pass to GnuPG’s --debug-level option. See the GnuPG man page for the list of valid options. If False, debug output is not generated by the GnuPG binary. If True, defaults to --debug-level basic.
- keyring (str) – Name of keyring file containing public key data. If unspecified, defaults to pubring.gpg in the homedir directory.
- secring (str) – Name of alternative secret keyring file to use. If left unspecified, this will default to using secring.gpg in the homedir directory, and create that file if it does not exist.
- options (list) – A list of additional options to pass to the GnuPG binary.
Raises: A RuntimeError with explanation message if there is a problem invoking GnuPG.
Example:
>>> import gnupg GnuPG logging disabled... >>> gpg = gnupg.GPG(homedir='doctests') >>> gpg.keyring './doctests/pubring.gpg' >>> gpg.secring './doctests/secring.gpg' >>> gpg.use_agent False >>> gpg.binary '/usr/bin/gpg'
- _batch_limit = 25¶
- _create_trustdb()¶
Create the trustdb file in our homedir, if it doesn’t exist.
- _export_ownertrust(trustdb=None)¶
Export ownertrust to a trustdb file.
If there is already a file named trustdb.gpg in the current GnuPG homedir, it will be renamed to trustdb.gpg.bak.
Parameters: trustdb (string) – The path to the trustdb.gpg file. If not given, defaults to 'trustdb.gpg' in the current GnuPG homedir.
- _fix_trustdb(trustdb=None)¶
Attempt to repair a broken trustdb.gpg file.
GnuPG>=2.0.x has this magical-seeming flag: –fix-trustdb. You’d think it would fix the the trustdb. Hah! It doesn’t. Here’s what it does instead:
(gpg)~/code/python-gnupg $ gpg2 --fix-trustdb gpg: You may try to re-create the trustdb using the commands: gpg: cd ~/.gnupg gpg: gpg2 --export-ownertrust > otrust.tmp gpg: rm trustdb.gpg gpg: gpg2 --import-ownertrust < otrust.tmp gpg: If that does not work, please consult the manual
Brilliant piece of software engineering right there.
Parameters: trustdb (str) – The path to the trustdb.gpg file. If not given, defaults to trustdb.gpg in the current GnuPG homedir.
- _import_ownertrust(trustdb=None)¶
Import ownertrust from a trustdb file.
Parameters: trustdb (str) – The path to the trustdb.gpg file. If not given, defaults to trustdb.gpg in the current GnuPG homedir.
- _parse_keys(result)¶
- _process_keys(keyids, check_sig=False)¶
- _remove_agent = True¶
- check_sigs(*keyids)¶
Validate the signatures for each of the keyids.
Return type: dict Returns: res.certs is a dictionary whose keys are the uids and whose values are a set of signature keyids.
- create_trustdb()¶
Create the trustdb file in our homedir, if it doesn’t exist.
- decrypt(message, **kwargs)¶
Decrypt the contents of a string or file-like object message.
Parameters: - message (file or str or io.BytesIO) – A string or file-like object to decrypt.
- always_trust (bool) – Instruct GnuPG to ignore trust checks.
- passphrase (str) – The passphrase for the secret key used for decryption.
- output (str) – A filename to write the decrypted output to.
- decrypt_file(filename, always_trust=False, passphrase=None, output=None)¶
Decrypt the contents of a file-like object filename .
Parameters:
- delete_keys(fingerprints, secret=False, subkeys=False)¶
Delete a key, or list of keys, from the current keyring.
The keys must be referred to by their full fingerprints for GnuPG to delete them. If secret=True, the corresponding secret keyring will be deleted from secring.
Parameters: - fingerprints (str or list or tuple) – A string, or a list/tuple of strings, representing the fingerprint(s) for the key(s) to delete.
- secret (bool) – If True, delete the corresponding secret key(s) also. (default: False)
- subkeys (bool) – If True, delete the secret subkey first, then the public key. (default: False) Same as: $gpg –delete-secret-and-public-key 0x12345678.
- encrypt(data, *recipients, **kwargs)¶
Encrypt the message contained in data to recipients.
Parameters: - data (str) – The file or bytestream to encrypt.
- recipients (str) – The recipients to encrypt to. Recipients must be specified keyID/fingerprint. Care should be taken in Python2.x to make sure that the given fingerprint is in fact a string and not a unicode object. Multiple recipients may be specified by doing GPG.encrypt(data, fpr1, fpr2, fpr3) etc.
- default_key (str) – The keyID/fingerprint of the key to use for signing. If given, data will be encrypted and signed.
- passphrase (str) – If given, and default_key is also given, use this passphrase to unlock the secret portion of the default_key to sign the encrypted data. Otherwise, if default_key is not given, but symmetric=True, then use this passphrase as the passphrase for symmetric encryption. Signing and symmetric encryption should not be combined when sending the data to other recipients, else the passphrase to the secret key would be shared with them.
- armor (bool) – If True, ascii armor the output; otherwise, the output will be in binary format. (Default: True)
- encrypt (bool) – If True, encrypt the data using the recipients public keys. (Default: True)
- symmetric (bool) – If True, encrypt the data to recipients using a symmetric key. See the passphrase parameter. Symmetric encryption and public key encryption can be used simultaneously, and will result in a ciphertext which is decryptable with either the symmetric passphrase or one of the corresponding private keys.
- always_trust (bool) – If True, ignore trust warnings on recipient keys. If False, display trust warnings. (default: True)
- output (str) – The output file to write to. If not specified, the encrypted output is returned, and thus should be stored as an object in Python. For example:
>>> import shutil >>> import gnupg >>> if os.path.exists("doctests"): ... shutil.rmtree("doctests") >>> gpg = gnupg.GPG(homedir="doctests") >>> key_settings = gpg.gen_key_input(key_type='RSA', ... key_length=1024, ... key_usage='ESCA', ... passphrase='foo') >>> key = gpg.gen_key(key_settings) >>> message = "The crow flies at midnight." >>> encrypted = str(gpg.encrypt(message, key.fingerprint)) >>> assert encrypted != message >>> assert not encrypted.isspace() >>> decrypted = str(gpg.decrypt(encrypted)) >>> assert not decrypted.isspace() >>> decrypted 'The crow flies at midnight.'
Parameters: - throw_keyids (bool) – If True, make all recipients keyids be zero’d out in packet information. This is the same as using hidden_recipients for all recipients. (Default: False).
- hidden_recipients (list) – A list of recipients that should have their keyids zero’d out in packet information.
- cipher_algo (str) – The cipher algorithm to use. To see available algorithms with your version of GnuPG, do: $ gpg –with-colons –list-config ciphername. The default cipher_algo, if unspecified, is 'AES256'.
- digest_algo (str) – The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: $ gpg –with-colons –list-config digestname. The default, if unspecified, is 'SHA512'.
- compress_algo (str) – The compression algorithm to use. Can be one of 'ZLIB', 'BZIP2', 'ZIP', or 'Uncompressed'.
See also
- expire(keyid, expiration_time='1y', passphrase=None, expire_subkeys=True)¶
- Changes GnuPG key expiration by passing in new time period (from now) through
- subprocess’s stdin
>>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> gpg.expire(key.fingerprint, '2w', 'good passphrase')
Parameters: - keyid (str) – key shortID, longID, email_address or fingerprint
- expiration_time (str) – 0 or number of days (d), or weeks (*w) , or months (*m) or years (*y) for when to expire the key, from today.
- passphrase (str) – passphrase used when creating the key, leave None otherwise
- expire_subkeys (bool) – to indicate whether the subkeys will also change the expiration time by the same period – default is True
Returns: The result giving status of the change in expiration... the new expiration date can be obtained by .list_keys()
- export_keys(keyids, secret=False, subkeys=False)¶
Export the indicated keyids.
Parameters:
- export_ownertrust(trustdb=None)¶
Export ownertrust to a trustdb file.
If there is already a file named trustdb.gpg in the current GnuPG homedir, it will be renamed to trustdb.gpg.bak.
Parameters: trustdb (string) – The path to the trustdb.gpg file. If not given, defaults to 'trustdb.gpg' in the current GnuPG homedir.
- fix_trustdb(trustdb=None)¶
Attempt to repair a broken trustdb.gpg file.
GnuPG>=2.0.x has this magical-seeming flag: –fix-trustdb. You’d think it would fix the the trustdb. Hah! It doesn’t. Here’s what it does instead:
(gpg)~/code/python-gnupg $ gpg2 --fix-trustdb gpg: You may try to re-create the trustdb using the commands: gpg: cd ~/.gnupg gpg: gpg2 --export-ownertrust > otrust.tmp gpg: rm trustdb.gpg gpg: gpg2 --import-ownertrust < otrust.tmp gpg: If that does not work, please consult the manual
Brilliant piece of software engineering right there.
Parameters: trustdb (str) – The path to the trustdb.gpg file. If not given, defaults to trustdb.gpg in the current GnuPG homedir.
- gen_key(input)¶
Generate a GnuPG key through batch file key generation. See GPG.gen_key_input() for creating the control input.
>>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> assert key.fingerprint
Parameters: input (dict) – A dictionary of parameters and values for the new key. Returns: The result mapping with details of the new key, which is a GenKey object.
- gen_key_input(separate_keyring=False, save_batchfile=False, testing=False, **kwargs)¶
Generate a batch file for input to gen_key().
The GnuPG batch file key generation feature allows unattended key generation by creating a file with special syntax and then providing it to: gpg –gen-key –batch. Batch files look like this:
Name-Real: AliceName-Email: alice@inter.netExpire-Date: 2014-04-01Key-Type: RSAKey-Length: 4096Key-Usage: certSubkey-Type: RSASubkey-Length: 4096Subkey-Usage: encrypt,sign,authPassphrase: sekrit%pubring foo.gpg%secring sec.gpg%commitwhich is what this function creates for you. All of the available, non-control parameters are detailed below (control parameters are the ones which begin with a ‘%’). For example, to generate the batch file example above, use like this:
>>> import gnupg GnuPG logging disabled... >>> from __future__ import print_function >>> gpg = gnupg.GPG(homedir='doctests') >>> alice = { 'name_real': 'Alice', ... 'name_email': 'alice@inter.net', ... 'expire_date': '2014-04-01', ... 'key_type': 'RSA', ... 'key_length': 4096, ... 'key_usage': '', ... 'subkey_type': 'RSA', ... 'subkey_length': 4096, ... 'subkey_usage': 'encrypt,sign,auth', ... 'passphrase': 'sekrit'} >>> alice_input = gpg.gen_key_input(**alice) >>> print(alice_input) Key-Type: RSA Subkey-Type: RSA Subkey-Usage: encrypt,sign,auth Expire-Date: 2014-04-01 Passphrase: sekrit Name-Real: Alice Name-Email: alice@inter.net Key-Length: 4096 Subkey-Length: 4096 %pubring ./doctests/alice.pubring.gpg %secring ./doctests/alice.secring.gpg %commit >>> alice_key = gpg.gen_key(alice_input) >>> assert alice_key is not None >>> assert alice_key.fingerprint is not None >>> message = "no one else can read my sekrit message" >>> encrypted = gpg.encrypt(message, alice_key.fingerprint) >>> assert isinstance(encrypted.data, str)
Parameters: - separate_keyring (bool) – Specify for the new key to be written to a separate pubring.gpg and secring.gpg. If True, gen_key() will automatically rename the separate keyring and secring to whatever the fingerprint of the generated key ends up being, suffixed with ‘.pubring’ and ‘.secring’ respectively.
- save_batchfile (bool) – Save a copy of the generated batch file to disk in a file named <name_real>.batch, where <name_real> is the name_real parameter stripped of punctuation, spaces, and non-ascii characters.
- testing (bool) – Uses a faster, albeit insecure random number generator to create keys. This should only be used for testing purposes, for keys which are going to be created and then soon after destroyed, and never for the generation of actual use keys.
- name_real (str) – The name field of the UID in the generated key.
- name_comment (str) – The comment in the UID of the generated key.
- name_email (str) – The email in the UID of the generated key. (default: $USER @ hostname ) Remember to use UTF-8 encoding for the entirety of the UID. At least one of name_real, name_comment, or name_email must be provided, or else no user ID is created.
- key_type (str) – One of ‘RSA’, ‘DSA’, ‘ELG-E’, or ‘default’. (default: ‘RSA’, if using GnuPG v1.x, otherwise ‘default’) Starts a new parameter block by giving the type of the primary key. The algorithm must be capable of signing. This is a required parameter. The algorithm may either be an OpenPGP algorithm number or a string with the algorithm name. The special value ‘default’ may be used for algo to create the default key type; in this case a key_usage should not be given and ‘default’ must also be used for subkey_type.
- key_length (int) – The requested length of the generated key in bits. (Default: 4096)
- key_grip (str) – hexstring This is an optional hexidecimal string which is used to generate a CSR or certificate for an already existing key. key_length will be ignored if this parameter is given.
- key_usage (str) – Space or comma delimited string of key usages. Allowed values are ‘encrypt’, ‘sign’, and ‘auth’. This is used to generate the key flags. Please make sure that the algorithm is capable of this usage. Note that OpenPGP requires that all primary keys are capable of certification, so no matter what usage is given here, the ‘cert’ flag will be on. If no ‘Key-Usage’ is specified and the ‘Key-Type’ is not ‘default’, all allowed usages for that particular algorithm are used; if it is not given but ‘default’ is used the usage will be ‘sign’.
- subkey_type (str) – This generates a secondary key (subkey). Currently only one subkey can be handled. See also key_type above.
- subkey_length (int) – The length of the secondary subkey in bits.
- subkey_usage (str) – Key usage for a subkey; similar to key_usage.
- expire_date (int or str) – Can be specified as an iso-date or as <int>[d|w|m|y] Set the expiration date for the key (and the subkey). It may either be entered in ISO date format (2000-08-15) or as number of days, weeks, month or years. The special notation “seconds=N” is also allowed to directly give an Epoch value. Without a letter days are assumed. Note that there is no check done on the overflow of the type used by OpenPGP for timestamps. Thus you better make sure that the given value make sense. Although OpenPGP works with time intervals, GnuPG uses an absolute value internally and thus the last year we can represent is 2105.
- creation_date (str) – Set the creation date of the key as stored in the key information and which is also part of the fingerprint calculation. Either a date like “1986-04-26” or a full timestamp like “19860426T042640” may be used. The time is considered to be UTC. If it is not given the current time is used.
- passphrase (str) – The passphrase for the new key. The default is to not use any passphrase. Note that GnuPG>=2.1.x will not allow you to specify a passphrase for batch key generation – GnuPG will ignore the passphrase parameter, stop, and ask the user for the new passphrase. However, we can put the command %no-protection into the batch key generation file to allow a passwordless key to be created, which can then have its passphrase set later with --edit-key.
- preferences (str) – Set the cipher, hash, and compression preference values for this key. This expects the same type of string as the sub-command ‘setpref’ in the –edit-key menu.
- revoker (str) – Should be given as ‘algo:fpr’ (case sensitive). Add a designated revoker to the generated key. Algo is the public key algorithm of the designated revoker (i.e. RSA=1, DSA=17, etc.) fpr is the fingerprint of the designated revoker. The optional ‘sensitive’ flag marks the designated revoker as sensitive information. Only v4 keys may be designated revokers.
- keyserver (str) – This is an optional parameter that specifies the preferred keyserver URL for the key.
- handle (str) – This is an optional parameter only used with the status lines KEY_CREATED and KEY_NOT_CREATED. string may be up to 100 characters and should not contain spaces. It is useful for batch key generation to associate a key parameter block with a status line.
Return type: str
Returns: A suitable input string for the GPG.gen_key() method, the latter of which will create the new keypair.
See this GnuPG Manual section for more details.
- import_keys(key_data)¶
Import the key_data into our keyring.
>>> import shutil >>> shutil.rmtree("doctests") >>> gpg = gnupg.GPG(homedir="doctests") >>> inpt = gpg.gen_key_input() >>> key1 = gpg.gen_key(inpt) >>> print1 = str(key1.fingerprint) >>> pubkey1 = gpg.export_keys(print1) >>> seckey1 = gpg.export_keys(print1,secret=True) >>> key2 = gpg.gen_key(inpt) >>> print2 = key2.fingerprint >>> seckeys = gpg.list_keys(secret=True) >>> pubkeys = gpg.list_keys() >>> assert print1 in seckeys.fingerprints >>> assert print1 in pubkeys.fingerprints >>> str(gpg.delete_keys(print1)) 'Must delete secret key first' >>> str(gpg.delete_keys(print1,secret=True)) 'ok' >>> str(gpg.delete_keys(print1)) 'ok' >>> pubkeys = gpg.list_keys() >>> assert not print1 in pubkeys.fingerprints >>> result = gpg.import_keys(pubkey1) >>> pubkeys = gpg.list_keys() >>> seckeys = gpg.list_keys(secret=True) >>> assert not print1 in seckeys.fingerprints >>> assert print1 in pubkeys.fingerprints >>> result = gpg.import_keys(seckey1) >>> assert result >>> seckeys = gpg.list_keys(secret=True) >>> assert print1 in seckeys.fingerprints
- import_ownertrust(trustdb=None)¶
Import ownertrust from a trustdb file.
Parameters: trustdb (str) – The path to the trustdb.gpg file. If not given, defaults to trustdb.gpg in the current GnuPG homedir.
- init¶
x.__init__(...) initializes x; see help(type(x)) for signature
- is_gpg1()¶
Returns true if using GnuPG <= 1.x.
- is_gpg2()¶
Returns true if using GnuPG >= 2.x.
- list_keys(secret=False)¶
List the keys currently in the keyring.
The GnuPG option ‘–show-photos’, according to the GnuPG manual, “does not work with –with-colons”, but since we can’t rely on all versions of GnuPG to explicitly handle this correctly, we should probably include it in the args.
>>> import shutil >>> shutil.rmtree("doctests") >>> gpg = GPG(homedir="doctests") >>> input = gpg.gen_key_input() >>> result = gpg.gen_key(input) >>> print1 = result.fingerprint >>> result = gpg.gen_key(input) >>> print2 = result.fingerprint >>> pubkeys = gpg.list_keys() >>> assert print1 in pubkeys.fingerprints >>> assert print2 in pubkeys.fingerprints
- list_packets(raw_data)¶
List the packet contents of a file.
- list_sigs(*keyids)¶
Get the signatures for each of the keyids.
>>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> assert key.fingerprint
Return type: dict Returns: res.sigs is a dictionary whose keys are the uids and whose values are a set of signature keyids.
- recv_keys(*keyids, **kwargs)¶
Import keys from a keyserver.
>>> gpg = gnupg.GPG(homedir="doctests") >>> key = gpg.recv_keys('hkp://pgp.mit.edu', '3FF0DB166A7476EA') >>> assert key
Parameters:
- sign(data, **kwargs)¶
Create a signature for a message string or file.
Note that this method is not for signing other keys. (In GnuPG’s terms, what we all usually call ‘keysigning’ is actually termed ‘certification’...) Even though they are cryptographically the same operation, GnuPG differentiates between them, presumedly because these operations are also the same as the decryption operation. If the key_usage``s ``C (certification), S (sign), and E (encrypt), were all the same key, the key would “wear down” through frequent signing usage – since signing data is usually done often – meaning that the secret portion of the keypair, also used for decryption in this scenario, would have a statistically higher probability of an adversary obtaining an oracle for it (or for a portion of the rounds in the cipher algorithm, depending on the family of cryptanalytic attack used).
In simpler terms: this function isn’t for signing your friends’ keys, it’s for something like signing an email.
Parameters: - data (str or file) – A string or file stream to sign.
- default_key (str) – The key to sign with.
- passphrase (str) – The passphrase to pipe to stdin.
- clearsign (bool) – If True, create a cleartext signature.
- detach (bool) – If True, create a detached signature.
- binary (bool) – If True, do not ascii armour the output.
- digest_algo (str) – The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: $ gpg –with-colons –list-config digestname. The default, if unspecified, is 'SHA512'.
- sign_key(keyid, default_key=None, passphrase=None)¶
sign (an imported) public key - keyid, with default secret key
>>> import gnupg >>> gpg = gnupg.GPG(homedir="doctests") >>> key_input = gpg.gen_key_input() >>> key = gpg.gen_key(key_input) >>> gpg.sign_key(key['fingerprint']) >>> gpg.list_sigs(key['fingerprint'])
Parameters: Returns: The result giving status of the key signing... success can be verified by gpg.list_sigs(keyid)
- verify(data)¶
Verify the signature on the contents of the string data.
>>> gpg = GPG(homedir="doctests") >>> input = gpg.gen_key_input(Passphrase='foo') >>> key = gpg.gen_key(input) >>> assert key >>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='bar') >>> assert not sig >>> sig = gpg.sign('hello',keyid=key.fingerprint,passphrase='foo') >>> assert sig >>> verify = gpg.verify(sig.data) >>> assert verify
- verify_file(file, sig_file=None)¶
Verify the signature on the contents of a file or file-like object. Can handle embedded signatures as well as detached signatures. If using detached signatures, the file containing the detached signature should be specified as the sig_file.
Parameters: - file (file) – A file descriptor object.
- sig_file (str) – A file containing the GPG signature data for file. If given, file is verified via this detached signature. Its type will be checked with _util._is_file().
meta module¶
Contains the meta and base classes which gnupg.GPG inherits from. Mostly, you shouldn’t ever need to touch anything in here, unless you’re doing some serious hacking.
Meta and base classes for hiding internal functions, and controlling attribute creation and handling.
- class GPGMeta[source]¶
Bases: type
Metaclass for changing the :meth:GPG.__init__ initialiser.
Detects running gpg-agent processes and the presence of a pinentry program, and disables pinentry so that python-gnupg can write the passphrase to the controlled GnuPG process without killing the agent.
Attr _agent_proc: If a gpg-agent process is currently running for the effective userid, then _agent_proc will be set to a psutil.Process for that process. - classmethod _find_agent()[source]¶
Discover if a gpg-agent process for the current euid is running.
If there is a matching gpg-agent process, set a psutil.Process instance containing the gpg-agent process’ information to cls._agent_proc.
For Unix systems, we check that the effective UID of this python-gnupg process is also the owner of the gpg-agent process. For Windows, we check that the usernames of the owners are the same. (Sorry Windows users; maybe you should switch to anything else.)
Returns: True if there exists a gpg-agent process running under the same effective user ID as that of this program. Otherwise, returns False.
- class GPGBase(binary=None, home=None, keyring=None, secring=None, use_agent=False, default_preference_list=None, ignore_homedir_permissions=False, verbose=False, options=None)[source]¶
Bases: object
Base class for storing properties and controlling process initialisation.
Const _result_map: A dict containing classes from _parsers, used for parsing results obtained from GnuPG commands. Const _decode_errors: How to handle encoding errors. Create a GPGBase.
This class is used to set up properties for controlling the behaviour of configuring various options for GnuPG, such as setting GnuPG’s homedir , and the paths to its binary and keyring .
Const binary: (str) The full path to the GnuPG binary.
Variables: - homedir – (InheritableProperty) The full path to the current setting for the GnuPG --homedir.
- _generated_keys – (InheritableProperty) Controls setting the directory for storing any keys which are generated with gen_key().
- keyring (str) – The filename in homedir to use as the keyring file for public keys.
- secring (str) – The filename in homedir to use as the keyring file for secret keys.
- __init__(binary=None, home=None, keyring=None, secring=None, use_agent=False, default_preference_list=None, ignore_homedir_permissions=False, verbose=False, options=None)[source]¶
Create a GPGBase.
This class is used to set up properties for controlling the behaviour of configuring various options for GnuPG, such as setting GnuPG’s homedir , and the paths to its binary and keyring .
Const binary: (str) The full path to the GnuPG binary.
Variables: - homedir – (InheritableProperty) The full path to the current setting for the GnuPG --homedir.
- _generated_keys – (InheritableProperty) Controls setting the directory for storing any keys which are generated with gen_key().
- keyring (str) – The filename in homedir to use as the keyring file for public keys.
- secring (str) – The filename in homedir to use as the keyring file for secret keys.
- binary_version = None¶
The version string of our GnuPG binary
- __remove_path__(prog=None, at_exit=True)[source]¶
Remove the directories containing a program from the system’s $PATH. If GPGBase.binary is in a directory being removed, it is linked to :file:’./gpg‘ in the current directory.
Parameters:
- _homedir_getter()[source]¶
Get the directory currently being used as GnuPG’s homedir.
If unspecified, use ~/.config/python-gnupg/
Return type: str Returns: The absolute path to the current GnuPG homedir.
- _homedir_setter(directory)[source]¶
Set the directory to use as GnuPG’s homedir.
If unspecified, use $HOME/.config/python-gnupg. If specified, ensure that the directory does not contain various shell escape characters. If directory is not found, it will be automatically created. Lastly, the direcory will be checked that the EUID has read and write permissions for it.
Parameters: directory (str) – A relative or absolute path to the directory to use for storing/accessing GnuPG’s files, including keyrings and the trustdb. Raises: RuntimeError if unable to find a suitable directory to use.
- homedir¶
- _generated_keys_getter()[source]¶
Get the homedir subdirectory for storing generated keys.
Return type: str Returns: The absolute path to the current GnuPG homedir.
- _generated_keys_setter(directory)[source]¶
Set the directory for storing generated keys.
If unspecified, use homedir()/generated-keys. If specified, ensure that the directory does not contain various shell escape characters. If directory isn’t found, it will be automatically created. Lastly, the directory will be checked to ensure that the current EUID has read and write permissions for it.
Parameters: directory (str) – A relative or absolute path to the directory to use for storing/accessing GnuPG’s files, including keyrings and the trustdb. Raises: RuntimeError if unable to find a suitable directory to use.
- _generated_keys¶
- _check_sane_and_get_gpg_version()[source]¶
Check that everything runs alright, and grab the gpg binary’s version number while we’re at it, storing it as binary_version.
Raises RuntimeError: if we cannot invoke the gpg binary.
- _make_args(args, passphrase=False)[source]¶
Make a list of command line elements for GPG.
The value of args will be appended only if it passes the checks in gnupg._parsers._sanitise(). The passphrase argument needs to be True if a passphrase will be sent to GnuPG, else False.
Parameters: - args (list) – A list of strings of options and flags to pass to GPG.binary. This is input safe, meaning that these values go through strict checks (see parsers._sanitise_list) before being passed to to the input file descriptor for the GnuPG process. Each string should be given exactly as it would be on the commandline interface to GnuPG, e.g. [“–cipher-algo AES256”, “–default-key A3ADB67A2CDB8B35”].
- passphrase (bool) – If True, the passphrase will be sent to the stdin file descriptor for the attached GnuPG process.
- _open_subprocess(args=None, passphrase=False)[source]¶
Open a pipe to a GPG subprocess and return the file objects for communicating with it.
Parameters: - args (list) – A list of strings of options and flags to pass to GPG.binary. This is input safe, meaning that these values go through strict checks (see parsers._sanitise_list) before being passed to to the input file descriptor for the GnuPG process. Each string should be given exactly as it would be on the commandline interface to GnuPG, e.g. [“–cipher-algo AES256”, “–default-key A3ADB67A2CDB8B35”].
- passphrase (bool) – If True, the passphrase will be sent to the stdin file descriptor for the attached GnuPG process.
- _read_response(stream, result)[source]¶
Reads all the stderr output from GPG, taking notice only of lines that begin with the magic [GNUPG:] prefix.
Calls methods on the response object for each valid token found, with the arg being the remainder of the status line.
Parameters: - stream – A byte-stream, file handle, or a subprocess.PIPE for parsing the status codes from the GnuPG process.
- result – The result parser class from _parsers ― the handle_status() method of that class will be called in order to parse the output of stream.
- _read_data(stream, result)[source]¶
Incrementally read from stream and store read data.
All data gathered from calling stream.read() will be concatenated and stored as result.data.
Parameters: - stream – An open file-like object to read() from.
- result – An instance of one of the result parsing classes from _result_map.
- _remove_agent = True¶
- _set_verbose(verbose)[source]¶
Check and set our verbose attribute. The debug-level must be a string or an integer. If it is one of the allowed strings, GnuPG will translate it internally to it’s corresponding integer level:
basic = 1-2 advanced = 3-5 expert = 6-8 guru = 9+
If it’s not one of the recognised string levels, then then entire argument is ignored by GnuPG. :(
To fix that stupid behaviour, if they wanted debugging but typo’d the string level (or specified verbose=True), we’ll default to ‘basic’ logging.
- _collect_output(process, result, writer=None, stdin=None)[source]¶
Drain the subprocesses output streams, writing the collected output to the result. If a writer thread (writing to the subprocess) is given, make sure it’s joined before returning. If a stdin stream is given, close it before returning.
- _handle_io(args, file, result, passphrase=False, binary=False)[source]¶
Handle a call to GPG - pass input data, collect output data.
- _sign_file(file, default_key=None, passphrase=None, clearsign=True, detach=False, binary=False, digest_algo='SHA512')[source]¶
Create a signature for a file.
Parameters: - file – The file stream (i.e. it’s already been open()’d) to sign.
- default_key (str) – The key to sign with.
- passphrase (str) – The passphrase to pipe to stdin.
- clearsign (bool) – If True, create a cleartext signature.
- detach (bool) – If True, create a detached signature.
- binary (bool) – If True, do not ascii armour the output.
- digest_algo (str) – The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: $ gpg --with-colons --list-config digestname. The default, if unspecified, is 'SHA512'.
- _encrypt(data, recipients, default_key=None, passphrase=None, armor=True, encrypt=True, symmetric=False, always_trust=True, output=None, throw_keyids=False, hidden_recipients=None, cipher_algo='AES256', digest_algo='SHA512', compress_algo='ZLIB')[source]¶
Encrypt the message read from the file-like object data.
Parameters: Warning
Care should be taken in Python2 to make sure that the given fingerprints for recipients are in fact strings and not unicode objects.
Parameters: - default_key (str) – The keyID/fingerprint of the key to use for signing. If given, data will be encrypted and signed.
- passphrase (str) – If given, and default_key is also given, use this passphrase to unlock the secret portion of the default_key to sign the encrypted data. Otherwise, if default_key is not given, but symmetric is True, then use this passphrase as the passphrase for symmetric encryption. Signing and symmetric encryption should not be combined when sending the data to other recipients, else the passphrase to the secret key would be shared with them.
- armor (bool) – If True, ascii armor the output; otherwise, the output will be in binary format. (Default: True)
- encrypt (bool) – If True, encrypt the data using the recipients public keys. (Default: True)
- symmetric (bool) – If True, encrypt the data to recipients using a symmetric key. See the passphrase parameter. Symmetric encryption and public key encryption can be used simultaneously, and will result in a ciphertext which is decryptable with either the symmetric passphrase or one of the corresponding private keys.
- always_trust (bool) – If True, ignore trust warnings on recipients keys. If False, display trust warnings. (default: True)
- output (str or file-like object) – The output file to write to. If not specified, the encrypted output is returned, and thus should be stored as an object in Python. For example:
>>> import shutil >>> import gnupg >>> if os.path.exists("doctests"): ... shutil.rmtree("doctests") >>> gpg = gnupg.GPG(homedir="doctests") >>> key_settings = gpg.gen_key_input(key_type='RSA', ... key_length=1024, ... key_usage='ESCA', ... passphrase='foo') >>> key = gpg.gen_key(key_settings) >>> message = "The crow flies at midnight." >>> encrypted = str(gpg.encrypt(message, key.fingerprint)) >>> assert encrypted != message >>> assert not encrypted.isspace() >>> decrypted = str(gpg.decrypt(encrypted)) >>> assert not decrypted.isspace() >>> decrypted 'The crow flies at midnight.'
Parameters: - throw_keyids (bool) – If True, make all recipients keyids be zero’d out in packet information. This is the same as using hidden_recipients for all recipients. (Default: False).
- hidden_recipients (list) – A list of recipients that should have their keyids zero’d out in packet information.
- cipher_algo (str) – The cipher algorithm to use. To see available algorithms with your version of GnuPG, do: $ gpg –with-colons –list-config ciphername. The default cipher_algo, if unspecified, is 'AES256'.
- digest_algo (str) – The hash digest to use. Again, to see which hashes your GnuPG is capable of using, do: $ gpg –with-colons –list-config digestname. The default, if unspecified, is 'SHA512'.
- compress_algo (str) – The compression algorithm to use. Can be one of 'ZLIB', 'BZIP2', 'ZIP', or 'Uncompressed'.
parsers module¶
These are classes for parsing both user inputs and status file descriptor flags from GnuPG’s output. The latter are used in order to determine what our GnuPG process is doing and retrieve information about its operations, which are stored in corresponding classes in _result_map. Some status flags aren’t handled yet – information on all of the flags (well, at least the documented ones…) can be found in the docs/DETAILS file in GnuPG’s source, which has been included here as well.
Classes for parsing GnuPG status messages and sanitising commandline options.
- exception ProtectedOption[source]¶
Bases: exceptions.Exception
Raised when the option passed to GPG is disallowed.
- exception UsageError[source]¶
Bases: exceptions.Exception
Raised when incorrect usage of the API occurs..
- _check_keyserver(location)[source]¶
Check that a given keyserver is a known protocol and does not contain shell escape characters.
Parameters: location (str) – A string containing the default keyserver. This should contain the desired keyserver protocol which is supported by the keyserver, for example, the default is 'hkp://wwwkeys .pgp.net'. Return type: str or None Returns: A string specifying the protocol and keyserver hostname, if the checks passed. If not, returns None.
- _check_preferences(prefs, pref_type=None)[source]¶
Check cipher, digest, and compression preference settings.
MD5 is not allowed. This is not 1994. SHA1 is allowed grudgingly.
- _fix_unsafe(shell_input)[source]¶
Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 shlex module.
Parameters: shell_input (str) – The input intended for the GnuPG process.
- _hyphenate(input, add_prefix=False)[source]¶
Change underscores to hyphens so that object attributes can be easily tranlated to GPG option names.
Parameters: Return type: str
Returns: The input with underscores changed to hyphens.
- _is_allowed(input)[source]¶
Check that an option or argument given to GPG is in the set of allowed options, the latter being a strict subset of the set of all options known to GPG.
Parameters: input (str) – An input meant to be parsed as an option or flag to the GnuPG process. Should be formatted the same as an option or flag to the commandline gpg, i.e. “–encrypt-files”.
Variables: - gnupg_options (frozenset) – All known GPG options and flags.
- allowed (frozenset) – All allowed GPG options and flags, e.g. all GPG options and flags which we are willing to acknowledge and parse. If we want to support a new option, it will need to have its own parsing class and its name will need to be added to this set.
Raises: UsageError if input is not a subset of the hard-coded set of all GnuPG options in _get_all_gnupg_options().
ProtectedOption if input is not in the set of allowed options.
Return type: str
Returns: The original input parameter, unmodified and unsanitized, if no errors occur.
- _is_hex(string)[source]¶
Check that a string is hexadecimal, with alphabetic characters in either upper or lower case and without whitespace.
Parameters: string (str) – The string to check.
- _is_string(thing)[source]¶
Python character arrays are a mess.
If Python2, check if thing is an unicode or a str. If Python3, check if thing is a str.
Parameters: thing – The thing to check. Returns: True if thing is a string according to whichever version of Python we’re running in.
- _sanitise(*args)[source]¶
Take an arg or the key portion of a kwarg and check that it is in the set of allowed GPG options and flags, and that it has the correct type. Then, attempt to escape any unsafe characters. If an option is not allowed, drop it with a logged warning. Returns a dictionary of all sanitised, allowed options.
Each new option that we support that is not a boolean, but instead has some additional inputs following it, i.e. “–encrypt-file foo.txt”, will need some basic safety checks added here.
GnuPG has three-hundred and eighteen commandline flags. Also, not all implementations of OpenPGP parse PGP packets and headers in the same way, so there is added potential there for messing with calls to GPG.
For information on the PGP message format specification, see RFC 1991.
If you’re asking, “Is this really necessary?”: No, not really – we could just follow the security precautions recommended by this xkcd.
Parameters: args (str) – (optional) The boolean arguments which will be passed to the GnuPG process. Return type: str Returns: sanitised
- _sanitise_list(arg_list)[source]¶
A generator for iterating through a list of gpg options and sanitising them.
Parameters: arg_list (list) – A list of options and flags for GnuPG. Return type: generator Returns: A generator whose next() method returns each of the items in arg_list after calling _sanitise() with that item as a parameter.
- _get_all_gnupg_options()[source]¶
Get all GnuPG options and flags.
This is hardcoded within a local scope to reduce the chance of a tampered GnuPG binary reporting falsified option sets, i.e. because certain options (namedly the --no-options option, which prevents the usage of gpg.conf files) are necessary and statically specified in gnupg._meta.GPGBase._make_args(), if the inputs into Python are already controlled, and we were to summon the GnuPG binary to ask it for its options, it would be possible to receive a falsified options set missing the --no-options option in response. This seems unlikely, and the method is stupid and ugly, but at least we’ll never have to debug whether or not an option actually disappeared in a different GnuPG version, or some funny business is happening.
These are the options as of GnuPG 1.4.12; the current stable branch of the 2.1.x tree contains a few more – if you need them you’ll have to add them in here.
Variables: gnupg_options – All known GPG options and flags. Return type: frozenset Returns: gnupg_options
- class KeyExpirationInterface(expiration_time, passphrase=None)[source]¶
Bases: object
Interface that guards against misuse of –edit-key combined with –command-fd
- class KeyExpirationResult(gpg)[source]¶
Bases: object
Handle status messages for key expiry It does not really have a job, but just to conform to the API
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class KeySigningResult(gpg)[source]¶
Bases: object
Handle status messages for key singing
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class GenKey(gpg)[source]¶
Bases: object
Handle status messages for key generation.
Calling the __str__() method of this class will return the generated key’s fingerprint, or a status string explaining the results.
- type = None¶
‘P’:= primary, ‘S’:= subkey, ‘B’:= both
- status = None¶
This will store a string describing the result of this operation. Current statuses are:
- ‘key not created’
- ‘key created’
- keyring = None¶
This will store the key’s public keyring filename, if gen_key_input() was called with separate_keyring=True.
- secring = None¶
This will store the key’s secret keyring filename, if : gen_key_input() was called with separate_keyring=True.
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class DeleteResult(gpg)[source]¶
Bases: object
Handle status messages for –delete-keys and –delete-secret-keys
- problem_reason = {'1': 'No such key', '3': 'Ambigious specification', '2': 'Must delete secret key first'}¶
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class Sign(gpg)[source]¶
Bases: object
Parse GnuPG status messages for signing operations.
Parameters: gpg – An instance of gnupg.GPG. - sig_type = None¶
The type of signature created.
- sig_algo = None¶
The algorithm used to create the signature.
- sig_hash_also = None¶
The hash algorithm used to create the signature.
- fingerprint = None¶
The fingerprint of the signing keyid.
- timestamp = None¶
The timestamp on the signature.
- what = None¶
xxx fill me in
- status = None¶
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class ListKeys(gpg)[source]¶
Bases: list
Handle status messages for –list-keys.
Handles pub and uid (relating the latter to the former). Don’t care about the following attributes/status messages (from doc/DETAILS):
crt = X.509 certificatecrs = X.509 certificate and private key availablessb = secret subkey (secondary key)uat = user attribute (same as user id except for field 10).pkd = public key data (special field format, see below)grp = reserved for gpgsmrvk = revocation key- pub(args)¶
- sec(args)¶
- class ImportResult(gpg)[source]¶
Bases: object
Parse GnuPG status messages for key import operations.
Start parsing the results of a key import operation.
Parameters: gpg (gnupg.GPG) – An instance of gnupg.GPG. - counts = None¶
Counts of all the status message results, _fields which have appeared.
- fingerprints = None¶
A list of strings containing the fingerprints of the GnuPG keyIDs imported.
- results = None¶
A list containing dictionaries with information gathered on keys imported.
- class ExportResult(gpg)[source]¶
Bases: object
Parse GnuPG status messages for key export operations.
Start parsing the results of a key export operation.
Parameters: gpg (gnupg.GPG) – An instance of gnupg.GPG. - counts = None¶
Counts of all the status message results, _fields which have appeared.
- fingerprints = None¶
A list of strings containing the fingerprints of the GnuPG keyIDs exported.
- class Verify(gpg)[source]¶
Bases: object
Parser for status messages from GnuPG for certifications and signature verifications.
People often mix these up, or think that they are the same thing. While it is true that certifications and signatures are the same cryptographic operation – and also true that both are the same as the decryption operation – a distinction is made for important reasons.
- A certification:
- is made on a key,
- can help to validate or invalidate the key owner’s identity,
- can assign trust levels to the key (or to uids and/or subkeys that the key contains),
- and can be used in absense of in-person fingerprint checking to try to build a path (through keys whose fingerprints have been checked) to the key, so that the identity of the key’s owner can be more reliable without having to actually physically meet in person.
- A signature:
- is created for a file or other piece of data,
- can help to prove that the data hasn’t been altered,
- and can help to prove that the data was sent by the person(s) in possession of the private key that created the signature, and for parsing portions of status messages from decryption operations.
There are probably other things unique to each that have been scatterbrainedly omitted due to the programmer sitting still and staring at GnuPG debugging logs for too long without snacks, but that is the gist of it.
Create a parser for verification and certification commands.
Parameters: gpg – An instance of gnupg.GPG. - TRUST_UNDEFINED = 0¶
- TRUST_NEVER = 1¶
- TRUST_MARGINAL = 2¶
- TRUST_FULLY = 3¶
- TRUST_ULTIMATE = 4¶
- TRUST_LEVELS = {'TRUST_UNDEFINED': 0, 'TRUST_FULLY': 3, 'TRUST_NEVER': 1, 'TRUST_MARGINAL': 2, 'TRUST_ULTIMATE': 4}¶
- valid = None¶
True if the signature is valid, False otherwise.
- status = None¶
A string describing the status of the signature verification. Can be one of signature bad, signature good, signature valid, signature error, decryption failed, no public key, key exp, or key rev.
- fingerprint = None¶
The fingerprint of the signing keyid.
- pubkey_fingerprint = None¶
The fingerprint of the corresponding public key, which may be different if the signature was created with a subkey.
- key_id = None¶
The keyid of the signing key.
- signature_id = None¶
The id of the signature itself.
- creation_date = None¶
The creation date of the signing key.
- timestamp = None¶
The timestamp of the purported signature, if we are unable to parse and/or validate it.
- sig_timestamp = None¶
The timestamp for when the valid signature was created.
- username = None¶
The userid of the signing key which was used to create the signature.
- expire_timestamp = None¶
When the signing key is due to expire.
- trust_level = None¶
An integer 0-4 describing the trust level of the signature.
- trust_text = None¶
The string corresponding to the trust_level number.
- subpackets = None¶
The subpackets. These are stored as a dictionary, in the following form:
- Verify.subpackets = {‘SUBPACKET_NUMBER’: {‘flags’: FLAGS,
- ‘length’: LENGTH, ‘data’: DATA},
‘ANOTHER_SUBPACKET_NUMBER’: {...}}
- notations = None¶
The signature or key notations. These are also stored as a dictionary, in the following form:
Verify.notations = {NOTATION_NAME: NOTATION_DATA}For example, the Bitcoin core developer, Peter Todd, encodes in every signature the header of the latest block on the Bitcoin blockchain (to prove that a GnuPG signature that Peter made was made after a specific point in time). These look like:
gpg: Signature notation: blockhash@bitcoin.org=000000000000000006f793d4461ee3e756ff04cc62581c96a42ed67dc233da3a
Which python-gnupg would store as:
Verify.notations['blockhash@bitcoin.org‘] = ‘000000000000000006f793d4461ee3e756ff04cc62581c96a42ed67dc233da3a’
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class Crypt(gpg)[source]¶
Bases: gnupg._parsers.Verify
Parser for internal status messages from GnuPG for --encrypt, --decrypt, and --decrypt-files.
- data = None¶
A string containing the encrypted or decrypted data.
- ok = None¶
True if the decryption/encryption process turned out okay.
- status = None¶
A string describing the current processing status, or error, if one has occurred.
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
- class ListPackets(gpg)[source]¶
Bases: object
Handle status messages for –list-packets.
- status = None¶
A string describing the current processing status, or error, if one has occurred.
- need_passphrase = None¶
True if the passphrase to a public/private keypair is required.
- need_passphrase_sym = None¶
True if a passphrase for a symmetric key is required.
- userid_hint = None¶
The keyid and uid which this data is encrypted to.
- key = None¶
The first key that we detected that a message was encrypted to. This is provided for backwards compatibility. As of Issue #77_, the encrypted_to attribute should be used instead.
- encrypted_to = None¶
A list of keyid’s that the message has been encrypted to.
- _handle_status(key, value)[source]¶
Parse a status code from the attached GnuPG process.
Raises: ValueError if the status message is unknown.
util module¶
You shouldn’t really need to mess with this module either, it mostly deals with low-level IO and file handling operations, de-/en- coding issues, and setting up basic package facilities such as logging.
Extra utilities for python-gnupg.
- exception GnuPGVersionError[source]¶
Bases: exceptions.ValueError
Raised when we couldn’t parse GnuPG’s version info.
- find_encodings(enc=None, system=False)[source]¶
Find functions for encoding translations for a specific codec.
Parameters: Raises: :exc:LookupError if the normalized codec, enc, cannot be found in Python’s encoding translation map.
Easy object-oriented representation of contributor info.
Parameters:
- _copy_data(instream, outstream)[source]¶
Copy data from one stream to another.
Parameters: - instream (io.BytesIO or io.StringIO or file) – A byte stream or open file to read from.
- outstream (file) – The file descriptor of a tmpfile to write to.
- _create_if_necessary(directory)[source]¶
Create the specified directory, if necessary.
Parameters: directory (str) – The directory to use. Return type: bool Returns: True if no errors occurred and the directory was created or existed beforehand, False otherwise.
- create_uid_email(username=None, hostname=None)[source]¶
Create an email address suitable for a UID on a GnuPG key.
Parameters: Return type: str
Returns: A string formatted as <username>@<hostname>.
- _deprefix(line, prefix, callback=None)[source]¶
Remove the prefix string from the beginning of line, if it exists.
Parameters: - line (string) – A line, such as one output by GnuPG’s status-fd.
- prefix (string) – A substring to remove from the beginning of line. Case insensitive.
- callback (callable) – Function to call if the prefix is found. The signature to callback will be only one argument, the line without the prefix, i.e. callback(line).
Return type: string
Returns: If the prefix was found, the line without the prefix is returned. Otherwise, the original line is returned.
- _find_binary(binary=None)[source]¶
Find the absolute path to the GnuPG binary.
Also run checks that the binary is not a symlink, and check that our process real uid has exec permissions.
Parameters: binary (str) – The path to the GnuPG binary. Raises: RuntimeError if it appears that GnuPG is not installed. Return type: str Returns: The absolute path to the GnuPG binary to use, if no exceptions occur.
- _has_readwrite(path)[source]¶
Determine if the real uid/gid of the executing user has read and write permissions for a directory or a file.
Parameters: path (str) – The path to the directory or file to check permissions for. Return type: bool Returns: True if real uid/gid has read+write permissions, False otherwise.
- _is_file(filename)[source]¶
Check that the size of the thing which is supposed to be a filename has size greater than zero, without following symbolic links or using :func:os.path.isfile.
Parameters: filename – An object to check. Return type: bool Returns: True if filename is file-like, False otherwise.
- _is_stream(input)[source]¶
Check that the input is a byte stream.
Parameters: input – An object provided for reading from or writing to. Return type: bool Returns: True if :param:input is a stream, False if otherwise.
- _is_string(thing)[source]¶
Check that thing is a string. The definition of the latter depends upon the Python version.
Parameters: thing – The thing to check if it’s a string. Return type: bool Returns: True if thing is string (or unicode in Python2).
- _is_bytes(thing)[source]¶
Check that thing is bytes.
Parameters: thing – The thing to check if it’s bytes. Return type: bool Returns: True if thing is bytes or a bytearray.
- _is_list_or_tuple(instance)[source]¶
Check that instance is a list or tuple.
Parameters: instance – The object to type check. Return type: bool Returns: True if instance is a list or tuple, False otherwise.
- _is_gpg1(version)[source]¶
Returns True if using GnuPG version 1.x.
Parameters: version (tuple) – A tuple of three integers indication major, minor, and micro version numbers.
- _is_gpg2(version)[source]¶
Returns True if using GnuPG version 2.x.
Parameters: version (tuple) – A tuple of three integers indication major, minor, and micro version numbers.
- _make_binary_stream(thing, encoding=None, armor=True)[source]¶
Encode thing, then make it stream/file-like.
Parameters: thing – The thing to turn into a encoded stream. Return type: io.BytesIO or io.StringIO. Returns: The encoded thing, wrapped in an io.BytesIO (if available), otherwise wrapped in a io.StringIO.
- _make_passphrase(length=None, save=False, file=None)[source]¶
Create a passphrase and write it to a file that only the user can read.
This is not very secure, and should not be relied upon for actual key passphrases.
Parameters:
- _make_random_string(length)[source]¶
Returns a random lowercase, uppercase, alphanumerical string.
Parameters: length (int) – The length in bytes of the string to generate.
- _match_version_string(version)[source]¶
Sort a binary version string into major, minor, and micro integers.
Parameters: version (str) – A version string in the form x.x.x Raises GnuPGVersionError: if the version string couldn’t be parsed. Return type: tuple Returns: A 3-tuple of integers, representing the (MAJOR, MINOR, MICRO) version numbers. For example: _match_version_string("2.1.3")
would return (2, 1, 3).
- _next_year()[source]¶
Get the date of today plus one year.
Return type: str Returns: The date of this day next year, in the format ‘%Y-%m-%d’.
- _threaded_copy_data(instream, outstream)[source]¶
Copy data from one stream to another in a separate thread.
Wraps _copy_data() in a threading.Thread.
Parameters: - instream (io.BytesIO or io.StringIO) – A byte stream to read from.
- outstream (file) – The file descriptor of a tmpfile to write to.
- _which(executable, flags=1, abspath_only=False, disallow_symlinks=False)[source]¶
Borrowed from Twisted’s :mod:twisted.python.proutils .
Search PATH for executable files with the given name.
On newer versions of MS-Windows, the PATHEXT environment variable will be set to the list of file extensions for files considered executable. This will normally include things like ”.EXE”. This fuction will also find files with the given name ending with any of these extensions.
On MS-Windows the only flag that has any meaning is os.F_OK. Any other flags will be ignored.
Note: This function does not help us prevent an attacker who can already manipulate the environment’s PATH settings from placing malicious code higher in the PATH. It also does happily follows links.
Parameters: Return type: list
Returns: A list of the full paths to files found, in the order in which they were found.
- _write_passphrase(stream, passphrase, encoding)[source]¶
Write the passphrase from memory to the GnuPG process’ stdin.
Parameters:
About this fork¶
This is a modified version of python-gnupg, (forked from version 0.3.2) which was created by Vinay Sajip, which itself is a modification of GPG.py written by Steve Traugott, which in turn is a modification of the pycrypto GnuPG interface written by A.M. Kuchling.
This version is patched to sanitize untrusted inputs, due to the necessity of executing subprocess.Popen([...], shell=True) in order to communicate with GnuPG. Several speed improvements were also made based on code profiling, and the API has been cleaned up to support an easier, more Pythonic, interaction.
Previous Authors’ Documentation¶
- Steve Traugott’s documentation:
- Portions of this module are derived from A.M. Kuchling’s well-designedGPG.py, using Richard Jones’ updated version 1.3, which can be found inthe pycrypto CVS repository on Sourceforge:This module is not forward-compatible with amk’s; some of the oldinterface has changed. For instance, since I’ve added decryptfunctionality, I elected to initialize with a ‘gpghome’ argument insteadof ‘keyring’, so that gpg can find both the public and secret keyrings.I’ve also altered some of the returned objects in order for the caller tonot have to know as much about the internals of the result classes.While the rest of ISconf is released under the GPL, I am releasing thissingle file under the same terms that A.M. Kuchling used for pycrypto.Steve Traugott, stevegt@terraluna.orgThu Jun 23 21:27:20 PDT 2005
- Vinay Sajip’s documentation:
- This version of the module has been modified from Steve Traugott’s versionVinay Sajip to make use of the subprocess module (Steve’s version usesos.fork() and so does not work on Windows). Renamed to gnupg.py to avoidconfusion with the previous versions.A unittest harness (test_gnupg.py) has also been added.Modifications Copyright (C) 2008-2012 Vinay Sajip. All rights reserved.