本文整理汇总了Python中mailpile.crypto.gpgi.GnuPG类的典型用法代码示例。如果您正苦于以下问题:Python GnuPG类的具体用法?Python GnuPG怎么用?Python GnuPG使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GnuPG类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_vcards
def get_vcards(self):
if not self.config.active:
return []
gnupg = GnuPG()
keys = gnupg.list_keys()
results = []
vcards = {}
for key in keys.values():
vcls = [VCardLine(name="KEY",
value=self.VCL_KEY_FMT % key)]
card = None
emails = []
for uid in key["uids"]:
if "email" in uid and uid["email"]:
vcls.append(VCardLine(name="email", value=uid["email"]))
card = card or vcards.get(uid['email'])
emails.append(uid["email"])
if "name" in uid and uid["name"]:
name = uid["name"]
vcls.append(VCardLine(name="fn", value=name))
if card and emails:
card.add(*vcls)
elif emails:
# This is us taking care to only create one card for each
# set of e-mail addresses.
card = SimpleVCard(*vcls)
for email in emails:
vcards[email] = card
results.append(card)
return results
示例2: command
def command(self):
args = self.args[:]
for q in self.data.get('q', []):
args.extend(q.split())
g = GnuPG()
return g.search_key(" ".join(args))
示例3: lookup_crypto_keys
def lookup_crypto_keys(session, address):
x = {}
scores = []
for handler in KEY_LOOKUP_HANDLERS:
h = handler(session)
r, s = h.lookup(address)
for key, value in r.iteritems():
if key in x:
x[key].update(value)
else:
x[key] = value
x[key]["origin"] = []
x[key]["origin"].append(h.NAME)
scores.append(s)
for scoreset in scores:
for key, value in scoreset.iteritems():
if key not in x:
continue
if "score" not in x[key]:
x[key]["score"] = 0
x[key]["score"] += value
g = GnuPG()
known_keys_list = g.list_keys()
for key in x.keys():
x[key]["fingerprint"] = key
x[key]["score"] += crypto_keys_scorer(known_keys_list, key)
x = [i for i in x.values()]
x.sort(key=lambda k: -k["score"])
return x
示例4: command
def command(self):
args = list(self.args)
for q in self.data.get("q", []):
args.extend(q.split())
g = GnuPG()
return g.search_key(" ".join(args))
示例5: get_vcards
def get_vcards(self):
if not self.config.active:
return []
gnupg = GnuPG()
keys = gnupg.list_keys()
results = []
vcards = {}
for key_id, key in keys.iteritems():
vcls = [VCardLine(name='KEY', value=self.VCL_KEY_FMT % key_id)]
card = None
emails = []
for uid in key.get('uids', []):
if uid.get('email'):
vcls.append(VCardLine(name='email', value=uid['email']))
card = card or vcards.get(uid['email'])
emails.append(uid['email'])
if uid.get('name'):
name = uid['name']
vcls.append(VCardLine(name='fn', value=name))
if card and emails:
card.add(*vcls)
elif emails:
# This is us taking care to only create one card for each
# set of e-mail addresses.
card = MailpileVCard(*vcls)
for email in emails:
vcards[email] = card
results.append(card)
return results
示例6: evaluate_pgp
def evaluate_pgp(self, tree, check_sigs=True, decrypt=False):
if 'text_parts' not in tree:
return tree
pgpdata = []
for part in tree['text_parts']:
if 'crypto' not in part:
part['crypto'] = {}
ei = si = None
if check_sigs:
if part['type'] == 'pgpbeginsigned':
pgpdata = [part]
elif part['type'] == 'pgpsignedtext':
pgpdata.append(part)
elif part['type'] == 'pgpsignature':
pgpdata.append(part)
try:
gpg = GnuPG()
message = ''.join([p['data'].encode(p['charset'])
for p in pgpdata])
si = pgpdata[1]['crypto']['signature'
] = gpg.verify(message)
pgpdata[0]['data'] = ''
pgpdata[2]['data'] = ''
except Exception, e:
print e
if decrypt:
if part['type'] in ('pgpbegin', 'pgptext'):
pgpdata.append(part)
elif part['type'] == 'pgpend':
pgpdata.append(part)
gpg = GnuPG()
(signature_info, encryption_info, text
) = gpg.decrypt(''.join([p['data'] for p in pgpdata]))
# FIXME: If the data is binary, we should provide some
# sort of download link or maybe leave the PGP
# blob entirely intact, undecoded.
text, charset = self.decode_text(text, binary=False)
ei = pgpdata[1]['crypto']['encryption'] = encryption_info
si = pgpdata[1]['crypto']['signature'] = signature_info
if encryption_info["status"] == "decrypted":
pgpdata[1]['data'] = text
pgpdata[0]['data'] = ""
pgpdata[2]['data'] = ""
# Bubbling up!
if (si or ei) and 'crypto' not in tree:
tree['crypto'] = {'signature': SignatureInfo(),
'encryption': EncryptionInfo()}
if si:
tree['crypto']['signature'].mix(si)
if ei:
tree['crypto']['encryption'].mix(ei)
示例7: command
def command(self):
keyid = self.data.get("keyid", self.args)
g = GnuPG()
res = []
for key in keyid:
res.append(g.recv_key(key))
return res
示例8: command
def command(self):
args = self.args[:]
for q in self.data.get('terms', []):
args.extend(q.split())
print "Querying PGP keyservers for: '%s'" % " ".join(args)
g = GnuPG()
return g.search_key(" ".join(args))
示例9: _import_key
def _import_key(self, result, keytype):
if keytype == "openpgp":
g = GnuPG(self.config)
res = g.import_keys(result[keytype])
if len(res["updated"]):
self._managed_keys_add(result["address"], keytype)
return res
else:
# We currently only support OpenPGP keys
return False
示例10: evaluate_pgp
def evaluate_pgp(self, tree, check_sigs=True, decrypt=False):
if "text_parts" not in tree:
return tree
pgpdata = []
for part in tree["text_parts"]:
if "crypto" not in part:
part["crypto"] = {}
ei = si = None
if check_sigs:
if part["type"] == "pgpbeginsigned":
pgpdata = [part]
elif part["type"] == "pgpsignedtext":
pgpdata.append(part)
elif part["type"] == "pgpsignature":
pgpdata.append(part)
try:
gpg = GnuPG()
message = "".join([p["data"].encode(p["charset"]) for p in pgpdata])
si = pgpdata[1]["crypto"]["signature"] = gpg.verify(message)
pgpdata[0]["data"] = ""
pgpdata[2]["data"] = ""
except Exception, e:
print e
if decrypt:
if part["type"] in ("pgpbegin", "pgptext"):
pgpdata.append(part)
elif part["type"] == "pgpend":
pgpdata.append(part)
gpg = GnuPG()
(signature_info, encryption_info, text) = gpg.decrypt("".join([p["data"] for p in pgpdata]))
# FIXME: If the data is binary, we should provide some
# sort of download link or maybe leave the PGP
# blob entirely intact, undecoded.
text, charset = self.decode_text(text, binary=False)
ei = pgpdata[1]["crypto"]["encryption"] = encryption_info
si = pgpdata[1]["crypto"]["signature"] = signature_info
if encryption_info["status"] == "decrypted":
pgpdata[1]["data"] = text
pgpdata[0]["data"] = ""
pgpdata[2]["data"] = ""
# Bubbling up!
if (si or ei) and "crypto" not in tree:
tree["crypto"] = {"signature": SignatureInfo(), "encryption": EncryptionInfo()}
if si:
tree["crypto"]["signature"].mix(si)
if ei:
tree["crypto"]["encryption"].mix(ei)
示例11: _check_password
def _check_password(self, password, account=None, fingerprint=None):
if account:
# We're going to keep punting on this for a while...
return True
elif fingerprint:
sps = SecurePassphraseStorage(password)
gpg = GnuPG(self.session.config)
status, sig = gpg.sign('OK', fromkey=fingerprint, passphrase=sps)
return (status == 0)
else:
return True
示例12: lookup_crypto_keys
def lookup_crypto_keys(session, address, event=None, allowremote=True):
def _calc_scores(x, scores):
for key in x.keys():
x[key]["score"] = 0
for scoreset in scores:
for key, value in scoreset.iteritems():
if key not in x:
continue
if "score" not in x[key]:
x[key]["score"] = 0
x[key]["score"] += value
return x
x = {}
scores = []
lastresult = {}
for handler in KEY_LOOKUP_HANDLERS:
h = handler(session)
if not allowremote and not h.LOCAL:
continue
if event:
m = _calc_scores(x, scores)
m = [i for i in m.values()]
m.sort(key=lambda k: -k["score"])
event.private_data = {"result": m, "runningsearch": h.NAME}
session.config.event_log.log_event(event)
r, s = h.lookup(address)
for key, value in r.iteritems():
if key in x:
x[key].update(value)
else:
x[key] = value
x[key]["origin"] = []
x[key]["origin"].append(h.NAME)
scores.append(s)
x = _calc_scores(x, scores)
g = GnuPG()
known_keys_list = g.list_keys()
for key in x.keys():
x[key]["fingerprint"] = key
x[key]["score"] += crypto_keys_scorer(known_keys_list, key)
x = [i for i in x.values()]
x.sort(key=lambda k: -k["score"])
if event:
event.private_data = {"result": x, "runningsearch": None}
session.config.event_log.log_event(event)
return x
示例13: _import_key
def _import_key(self, result, keytype):
if keytype == "openpgp":
g = GnuPG()
if self.config:
g.passphrase = self.config.gnupg_passphrase.get_reader()
res = g.import_keys(result[keytype])
if len(res["updated"]):
self._managed_keys_add(result["address"], keytype)
return res
else:
# We currently only support OpenPGP keys
return False
示例14: _do_login
def _do_login(self, user, password, load_index=False, redirect=False):
session, config = self.session, self.session.config
session_id = self.session.ui.html_variables.get('http_session')
# This prevents folks from sending us a DEFAULT user (upper case),
# which is an internal security bypass below.
user = user and user.lower()
if not user:
from mailpile.config import SecurePassphraseStorage
sps = SecurePassphraseStorage(password)
password = ''
try:
# Verify the passphrase
gpg = GnuPG(use_agent=False)
if gpg.is_available():
gpg.passphrase = sps.get_reader()
assert(gpg.sign('Sign This!')[0] == 0)
# Store the varified passphrase
config.gnupg_passphrase.data = sps.data
# Load the config and index, if necessary
if not config.loaded_config:
self._config()
if load_index:
self._idx()
else:
pass # FIXME: Start load in background
session.ui.debug('Good passphrase for %s' % session_id)
return self._logged_in(redirect=redirect)
else:
session.ui.debug('No GnuPG, checking DEFAULT user')
# No GnuPG, see if there is a DEFAULT user in the config
user = 'DEFAULT'
except (AssertionError, IOError):
session.ui.debug('Bad passphrase for %s' % session_id)
return self._error(_('Invalid passphrase, please try again'))
if user in config.logins or user == 'DEFAULT':
# FIXME: Salt and hash the password, check if it matches
# the entry in our user/password list (TODO).
# NOTE: This hack effectively disables auth without GnUPG
if user == 'DEFAULT':
session.ui.debug('FIXME: Unauthorized login allowed')
return self._logged_in(redirect=redirect)
raise Exception('FIXME')
self._error(_('Incorrect username or password'))
示例15: TransformOutgoing
def TransformOutgoing(self, sender, rcpts, msg, **kwargs):
matched = False
keydata = mutual = sender_keyid = key_binary = None
gnupg = GnuPG(self.config, event=GetThreadEvent())
profile = self._get_sender_profile(sender, kwargs)
vcard = profile['vcard']
if vcard is not None:
crypto_format = vcard.crypto_format
sender_keyid = vcard.pgp_key
if sender_keyid and 'autocrypt' in crypto_format:
key_binary = gnupg.get_minimal_key(key_id=sender_keyid,
user_id=sender)
if key_binary:
mutual = 'E' in crypto_format.split('+')[0].split(':')[-1]
msg["Autocrypt"] = make_autocrypt_header(
sender, key_binary, prefer_encrypt_mutual=mutual)
if 'encrypt' in msg.get('Encryption', '').lower():
gossip_list = []
for rcpt in rcpts:
# FIXME: Check if any of the recipients are in the BCC
# header; omit their keys if so?
try:
# This *should* always succeed: if we are encrypting,
# then the key we encrypt to should already be in
# the keychain.
if '#' in rcpt:
rcpt, rcpt_keyid = rcpt.split('#')
else:
# This happens when composing in the CLI.
rcpt_keyid = rcpt
if (rcpt != sender) and rcpt_keyid:
kb = gnupg.get_minimal_key(key_id=rcpt_keyid,
user_id=rcpt)
if kb:
gossip_list.append(make_autocrypt_header(
rcpt, kb, prefix='Autocrypt-Gossip'))
except (ValueError, IndexError):
pass
if len(gossip_list) > 1:
# No point gossiping peoples keys back to them alone.
for hdr in gossip_list:
msg.add_header('Autocrypt-Gossip', hdr)
matched = True
return sender, rcpts, msg, matched, True