本文整理汇总了Python中gnupg.GPG.list_keys方法的典型用法代码示例。如果您正苦于以下问题:Python GPG.list_keys方法的具体用法?Python GPG.list_keys怎么用?Python GPG.list_keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gnupg.GPG
的用法示例。
在下文中一共展示了GPG.list_keys方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_empty_config
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def write_empty_config(self, config, conffile):
rootdir = BaseDirectory.save_config_path('tuyau')
with file(conffile, 'wb') as fp:
config.write(fp)
g = GPG(gnupghome=os.path.join(rootdir, 'gnupg'))
g.list_keys()
示例2: encrypt
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def encrypt(file):
gpg_home = find_gpg_keys()
if ( gpg_home == ''):
print 'GPG keys not found'
sys.exit(1)
gpg = GPG(gnupghome=gpg_home, use_agent=True)
public_keys = gpg.list_keys()
key_id = public_keys[0]['keyid']
if ( os.path.isfile(file)):
if ( file.endswith('.gpg')):
print file + ' is already encrypted'
else:
stream = open(file, "rb")
status = gpg.encrypt_file(stream, key_id, passphrase='default_key', armor=False, always_trust=True,
output=file+'.gpg', symmetric=False)
stream.close()
if ( status.ok):
os.remove(file)
print file , ' successfully encrypted'
elif (os.path.isdir(file)):
for root, dirs, files in os.walk(file, topdown=True):
for name in files:
current_file = (os.path.join(root, name))
if ( current_file.endswith('.gpg') ):
print current_file + ' : is already encrypted'
else:
stream = open(current_file, "rb")
status = gpg.encrypt_file(stream, key_id, armor=True, always_trust=True, symmetric=False, output=current_file+'.gpg')
stream.close()
if ( status.ok ):
os.remove(current_file)
print current_file + ' successfully encrypted'
else:
print 'ERROR, file or directory not found'
示例3: decrypt
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def decrypt(file):
gpg_home = find_gpg_keys()
if ( gpg_home == ''):
print 'GPG keys not found'
sys.exit(1)
gpg = GPG(gnupghome=gpg_home, use_agent=True)
public_keys = gpg.list_keys()
key_id = public_keys[0]['keyid']
if ( os.path.isfile(file)):
if ( file.endswith('.gpg')):
stream = open(file, 'rb')
status = gpg.decrypt_file(stream, output=file[:-4])
if ( status.ok):
os.remove(file)
print file[:-4] + ' succesfully decrypted'
else:
print file + ' not encrypted'
elif ( os.path.isdir(file) ):
for root, dirs, files in os.walk(file, topdown=True):
for name in files:
current_file = (os.path.join(root, name))
if ( current_file.endswith('.gpg')):
stream = open(current_file, "rb")
status = gpg.decrypt_file(stream, output=current_file[:-4])
if ( status.ok ):
os.remove(current_file)
print current_file[:-4] + ' successfully decrypted'
else:
print current_file + ' not encrypted'
else:
print 'ERROR: file or directory not found'
示例4: get_expirations
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def get_expirations(keylist):
"""
This function is not implemented in GPG object class because need to operate
on the whole keys
"""
atfork()
try:
temp_gpgroot = os.path.join(GLSetting.gpgroot, "-expiration_check-%s" % random.randint(0, 0xFFFF) )
os.makedirs(temp_gpgroot, mode=0700)
gpexpire= GPG(gnupghome=temp_gpgroot, options="--trust-model always")
except Exception as excep:
log.err("Unable to setup expiration check environment: %s" % excep)
raise excep
try:
for key in keylist:
gpexpire.import_keys(key)
except Exception as excep:
log.err("Error in GPG import_keys: %s" % excep)
raise excep
try:
all_keys = gpexpire.list_keys()
except Exception as excep:
log.err("Error in GPG list_keys: %s" % excep)
raise excep
expirations = {}
for ak in all_keys:
expirations.update({ ak['fingerprint'] : ak['date']})
return expirations
示例5: delete
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def delete(self):
"""
Remove any keys for this address.
"""
gpg = GPG(gnupghome=GNUPG_HOME)
for key in gpg.list_keys():
if self.address in addresses_for_key(gpg, key):
gpg.delete_keys(key["fingerprint"], True)
gpg.delete_keys(key["fingerprint"])
super(Address, self).delete()
示例6: delete
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def delete(self):
"""
remove any keys for this address
"""
from email_extras.utils import addresses_for_key
gpg = GPG(gnupghome=GNUPG_HOME)
for key in gpg.list_keys():
if self.address in addresses_for_key(gpg, key):
gpg.delete_keys(key["fingerprint"], True)
gpg.delete_keys(key["fingerprint"])
super(Address, self).delete()
示例7: _generate_key
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def _generate_key(username):
gpg = GPG()
key_input = gpg.gen_key_input(key_type="RSA", key_length=1024, name_email=username+"@node.org", name_real=username)
entropy_thread = Process(target=generate_entropy)
entropy_thread.start()
key = gpg.gen_key(key_input)
entropy_thread.terminate()
keys = gpg.list_keys(True)
for k in keys:
if k.get("fingerprint") == key.fingerprint:
return k['keyid']
示例8: save
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def save(self, *args, **kwargs):
with TemporaryDirectory() as temp_dir:
gpg_keychain = GPG(gnupghome=temp_dir)
res = gpg_keychain.import_keys(self.key)
if not res:
handle_gpg_error(res, 'import')
if len(gpg_keychain.list_keys(True)) > 0:
raise GPGException("Will not import GPG private key!")
addresses = []
for key in res.results:
addresses.extend(addresses_for_key(gpg_keychain, key))
self.addresses = ', '.join(addresses)
operation = "Updating" if self.pk else "Creating"
logger.info("%s GPG key for: %s", operation, self.addresses)
super(Key, self).save(*args, **kwargs)
示例9: gpg_keys
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def gpg_keys(self):
"""
The GPG keyring path and list of key IDs.
:return: A tuple of: (path, key_ids)
The *path* is the absolute path to a keyring.
The *key_ids* is a list of key IDs added to the keyring.
:rtype: tuple
"""
home = self.working_dir
path = os.path.join(home, 'pubring.gpg')
key_list = self.config.get(constants.IMPORTER_CONFIG_KEY_GPG_KEYS, [])
gpg = GPG(gnupghome=home)
map(gpg.import_keys, key_list)
key_ids = [key['keyid'] for key in gpg.list_keys()]
return path, key_ids
示例10: clean_key
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
def clean_key(self):
"""
Raises ValidationError if the entered key is invalid or includes a GPG private key.
"""
data = self.cleaned_data['key']
with TemporaryDirectory() as temp_dir:
gpg_keychain = GPG(gnupghome=temp_dir)
res = gpg_keychain.import_keys(data)
if not res:
errors = [forms.ValidationError(_("Invalid key."), code='invalid')]
for attr in ['status', 'stderr']: # not all fields are always present
if hasattr(res, attr):
errors.append(forms.ValidationError("%(name)s: %(value)s",
params={'name': attr, 'value': getattr(res, attr)},
code=attr))
raise forms.ValidationError(errors)
if len(gpg_keychain.list_keys(True)) > 0: # check existance of private keys
raise forms.ValidationError(_("Import public keys only, no private keys! "
"You should consider the private key(s) compromised."),
code='private_key')
return data
示例11: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
class CryptoTxt:
"""Crypto operation provider for plaintext.
We use GnuPG for now. Support for X.509 and other options might
appear in the future.
"""
def __init__(self, gpg_binary, gpg_home):
"""Initialize the GnuPG instance."""
self.gpg_binary = gpg_binary
self.gpg_home = gpg_home
if not GPG:
raise TracError(_("Unable to load the python-gnupg module. "
"Please check and correct your installation."))
try:
self.gpg = GPG(gpgbinary=self.gpg_binary, gnupghome=self.gpg_home)
except ValueError:
raise TracError(_("Missing the crypto binary. Please check and "
"set full path with option 'gpg_binary'."))
else:
# get list of available public keys once for later use
self.pub_keys = self.gpg.list_keys()
def sign(self, content, private_key=None):
private_key = self._get_private_key(private_key)
cipher = self.gpg.sign(content, keyid=private_key, passphrase='')
return str(cipher)
def encrypt(self, content, pubkeys):
# always_trust needed for making it work with just any pubkey
cipher = self.gpg.encrypt(content, pubkeys, always_trust=True)
return str(cipher)
def sign_encrypt(self, content, pubkeys, private_key=None):
private_key = self._get_private_key(private_key)
# always_trust needed for making it work with just any pubkey
cipher = self.gpg.encrypt(content, pubkeys, always_trust=True,
sign=private_key, passphrase='')
return str(cipher)
def get_pubkey_ids(self, addr):
"""Find public key with UID matching address to encrypt to."""
pubkey_ids = []
if self.pub_keys and 'uids' in self.pub_keys[-1] and \
'fingerprint' in self.pub_keys[-1]:
# compile pattern before use for better performance
rcpt_re = re.compile(addr)
for k in self.pub_keys:
for uid in k['uids']:
match = rcpt_re.search(uid)
if match is not None:
# check for key expiration
if k['expires'] == '':
pubkey_ids.append(k['fingerprint'][-16:])
elif (time.time() + 60) < float(k['expires']):
pubkey_ids.append(k['fingerprint'][-16:])
break
return pubkey_ids
def _get_private_key(self, privkey=None):
"""Find private (secret) key to sign with."""
# read private keys from keyring
privkeys = self.gpg.list_keys(True) # True => private keys
if privkeys > 0 and 'fingerprint' in privkeys[-1]:
fingerprints = []
for k in privkeys:
fingerprints.append(k['fingerprint'])
else:
# no private key in keyring
return None
if privkey:
# check for existence of private key received as argument
# DEVEL: check for expiration as well
if 7 < len(privkey) <= 40:
for fp in fingerprints:
if fp.endswith(privkey):
# work with last 16 significant chars internally,
# even if only 8 are required in trac.ini
privkey = fp[-16:]
break
# no fingerprint matching key ID
else:
privkey = None
else:
# reset invalid key ID
privkey = None
else:
# select (last) private key from keyring
privkey = fingerprints[-1][-16:]
return privkey
示例12: PGPContext
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
class PGPContext(object):
def __init__(self, tempdirprefix=None):
if tempdirprefix is None:
tempdir = tempfile.mkdtemp()
else:
tempdir = tempfile.mkdtemp(prefix=tempdirprefix)
try:
gpgbinary='gpg'
if os.path.exists('/usr/bin/gpg1'):
gpgbinary='gpg1'
self.gnupg = GPG(gpgbinary=gpgbinary, gnupghome=tempdir, options=['--trust-model', 'always'])
self.gnupg.encoding = "UTF-8"
except OSError as excep:
log.err("Critical, OS error in operating with GnuPG home: %s", excep)
raise
except Exception as excep:
log.err("Unable to instance PGP object: %s" % excep)
raise
def load_key(self, key):
"""
@param key
@return: a dict with the expiration date and the key fingerprint
"""
try:
import_result = self.gnupg.import_keys(key)
except Exception as excep:
log.err("Error in PGP import_keys: %s", excep)
raise errors.InputValidationError
if not import_result.fingerprints:
raise errors.InputValidationError
fingerprint = import_result.fingerprints[0]
# looking if the key is effectively reachable
try:
all_keys = self.gnupg.list_keys()
except Exception as excep:
log.err("Error in PGP list_keys: %s", excep)
raise errors.InputValidationError
expiration = datetime.utcfromtimestamp(0)
for k in all_keys:
if k['fingerprint'] == fingerprint:
if k['expires']:
expiration = datetime.utcfromtimestamp(int(k['expires']))
break
return {
'fingerprint': fingerprint,
'expiration': expiration
}
def encrypt_file(self, key_fingerprint, input_file, output_path):
"""
Encrypt a file with the specified PGP key
"""
encrypted_obj = self.gnupg.encrypt_file(input_file, str(key_fingerprint), output=output_path)
if not encrypted_obj.ok:
raise errors.InputValidationError
return encrypted_obj, os.stat(output_path).st_size
def encrypt_message(self, key_fingerprint, plaintext):
"""
Encrypt a text message with the specified key
"""
encrypted_obj = self.gnupg.encrypt(plaintext, str(key_fingerprint))
if not encrypted_obj.ok:
raise errors.InputValidationError
return str(encrypted_obj)
def __del__(self):
try:
shutil.rmtree(self.gnupg.gnupghome)
except Exception as excep:
log.err("Unable to clean temporary PGP environment: %s: %s", self.gnupg.gnupghome, excep)
示例13: TempGPGWrapper
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
class TempGPGWrapper(object):
"""
A context manager that wraps a temporary GPG keyring which only contains
the keys given at object creation.
"""
def __init__(self, keys=None, gpgbinary=None):
"""
Create an empty temporary keyring and import any given C{keys} into
it.
:param keys: OpenPGP key, or list of.
:type keys: OpenPGPKey or list of OpenPGPKeys
:param gpgbinary: Name for GnuPG binary executable.
:type gpgbinary: C{str}
"""
self._gpg = None
self._gpgbinary = gpgbinary
if not keys:
keys = list()
if not isinstance(keys, list):
keys = [keys]
self._keys = keys
for key in keys:
leap_assert_type(key, OpenPGPKey)
def __enter__(self):
"""
Build and return a GPG keyring containing the keys given on
object creation.
:return: A GPG instance containing the keys given on object creation.
:rtype: gnupg.GPG
"""
self._build_keyring()
return self._gpg
def __exit__(self, exc_type, exc_value, traceback):
"""
Ensure the gpg is properly destroyed.
"""
# TODO handle exceptions and log here
self._destroy_keyring()
def _build_keyring(self):
"""
Create a GPG keyring containing the keys given on object creation.
:return: A GPG instance containing the keys given on object creation.
:rtype: gnupg.GPG
"""
privkeys = [key for key in self._keys if key and key.private is True]
publkeys = [key for key in self._keys if key and key.private is False]
# here we filter out public keys that have a correspondent
# private key in the list because the private key_data by
# itself is enough to also have the public key in the keyring,
# and we want to count the keys afterwards.
privfps = map(lambda privkey: privkey.fingerprint, privkeys)
publkeys = filter(
lambda pubkey: pubkey.fingerprint not in privfps, publkeys)
listkeys = lambda: self._gpg.list_keys()
listsecretkeys = lambda: self._gpg.list_keys(secret=True)
self._gpg = GPG(binary=self._gpgbinary,
homedir=tempfile.mkdtemp())
leap_assert(len(listkeys()) is 0, 'Keyring not empty.')
# import keys into the keyring:
# concatenating ascii-armored keys, which is correctly
# understood by GPG.
self._gpg.import_keys("".join(
[x.key_data for x in publkeys + privkeys]))
# assert the number of keys in the keyring
leap_assert(
len(listkeys()) == len(publkeys) + len(privkeys),
'Wrong number of public keys in keyring: %d, should be %d)' %
(len(listkeys()), len(publkeys) + len(privkeys)))
leap_assert(
len(listsecretkeys()) == len(privkeys),
'Wrong number of private keys in keyring: %d, should be %d)' %
(len(listsecretkeys()), len(privkeys)))
def _destroy_keyring(self):
"""
Securely erase the keyring.
"""
# TODO: implement some kind of wiping of data or a more
# secure way that
# does not write to disk.
try:
for secret in [True, False]:
for key in self._gpg.list_keys(secret=secret):
self._gpg.delete_keys(
key['fingerprint'],
secret=secret)
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
#.........这里部分代码省略.........
return sanitized
raise errors.InvalidInputFormat("Malformed PGP key block")
def validate_key(self, armored_key):
"""
@param armored_key:
@return: True or False, True only if a key is effectively importable and listed.
"""
# or raise InvalidInputFormat
sanitized_gpgasc = self.sanitize_gpg_string(armored_key)
try:
self.ke = self.gpgh.import_keys(sanitized_gpgasc)
except Exception as excep:
log.err("Error in GPG import_keys: %s" % excep)
return False
# Error reported in stderr may just be warning, this is because is not raise an exception here
# if self.ke.stderr:
# log.err("Receiver %s in uploaded GPG key has raise and alarm:\n< %s >" %
# (self.receiver_desc['username'], (self.ke.stderr.replace("\n", "\n "))[:-3]))
if not (hasattr(self.ke, 'results') and len(self.ke.results) == 1 and self.ke.results[0].has_key('fingerprint')):
log.err("User error: unable to import GPG key in the keyring")
return False
# else, the key has been loaded and we extract info about that:
self.fingerprint = self.ke.results[0]['fingerprint']
# looking if the key is effectively reachable
try:
all_keys = self.gpgh.list_keys()
except Exception as excep:
log.err("Error in GPG list_keys: %s" % excep)
return False
self.keyinfo = u""
for key in all_keys:
if key['fingerprint'] == self.fingerprint:
self.keyinfo += "Key length %s" % key['length']
try:
for uid in key['uids']:
self.keyinfo += "\n\t%s" % uid
except Exception as excep:
log.err("Error in GPG key format/properties: %s" % excep)
return False
if not len(self.keyinfo):
log.err("Key apparently imported but unable to be extracted info")
return False
return True
def encrypt_file(self, plainpath, filestream, output_path):
"""
@param gpg_key_armor:
@param plainpath:
@return:
"""
if not self.validate_key(self.receiver_desc['gpg_key_armor']):
raise errors.GPGKeyInvalid
示例15: GLBPGP
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import list_keys [as 别名]
class GLBPGP(object):
"""
PGP has not a dedicated class, because one of the function is called inside a transact, and
I'm not quite confident on creating an object that operates on the filesystem knowing
that would be run also on the Storm cycle.
"""
def __init__(self):
"""
every time is needed, a new keyring is created here.
"""
try:
temp_pgproot = os.path.join(GLSettings.pgproot, "%s" % rstr.xeger(r'[A-Za-z0-9]{8}'))
os.makedirs(temp_pgproot, mode=0700)
self.pgph = GPG(gnupghome=temp_pgproot, options=['--trust-model', 'always'])
self.pgph.encoding = "UTF-8"
except OSError as ose:
log.err("Critical, OS error in operating with GnuPG home: %s" % ose)
raise
except Exception as excep:
log.err("Unable to instance PGP object: %s" % excep)
raise
def load_key(self, key):
"""
@param key:
@return: True or False, True only if a key is effectively importable and listed.
"""
try:
import_result = self.pgph.import_keys(key)
except Exception as excep:
log.err("Error in PGP import_keys: %s" % excep)
raise errors.PGPKeyInvalid
if len(import_result.fingerprints) != 1:
raise errors.PGPKeyInvalid
fingerprint = import_result.fingerprints[0]
# looking if the key is effectively reachable
try:
all_keys = self.pgph.list_keys()
except Exception as excep:
log.err("Error in PGP list_keys: %s" % excep)
raise errors.PGPKeyInvalid
info = u""
expiration = datetime.utcfromtimestamp(0)
for key in all_keys:
if key['fingerprint'] == fingerprint:
if key['expires']:
expiration = datetime.utcfromtimestamp(int(key['expires']))
exp_date = datetime_to_day_str(expiration)
else:
exp_date = u'Never'
info += "Key length: %s\n" % key['length']
info += "Key expiration: %s\n" % exp_date
try:
for uid in key['uids']:
info += "\t%s\n" % uid
except Exception as excep:
log.err("Error in PGP key format/properties: %s" % excep)
raise errors.PGPKeyInvalid
break
if not len(info):
log.err("Key apparently imported but unable to reload it")
raise errors.PGPKeyInvalid
return {
'fingerprint': fingerprint,
'expiration': expiration,
'info': info
}
def encrypt_file(self, key_fingerprint, plainpath, filestream, output_path):
"""
@param pgp_key_public:
@param plainpath:
@return:
"""
encrypt_obj = self.pgph.encrypt_file(filestream, str(key_fingerprint))
if not encrypt_obj.ok:
raise errors.PGPKeyInvalid
log.debug("Encrypting for key %s file %s (%d bytes)" %
(key_fingerprint,
plainpath, len(str(encrypt_obj))))
encrypted_path = os.path.join(os.path.abspath(output_path),
"pgp_encrypted-%s" % rstr.xeger(r'[A-Za-z0-9]{16}'))
try:
with open(encrypted_path, "w+") as f:
f.write(str(encrypt_obj))
#.........这里部分代码省略.........