本文整理汇总了Python中gnupg.GPG.sign方法的典型用法代码示例。如果您正苦于以下问题:Python GPG.sign方法的具体用法?Python GPG.sign怎么用?Python GPG.sign使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gnupg.GPG
的用法示例。
在下文中一共展示了GPG.sign方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: str
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import sign [as 别名]
cnx = sqlite3.connect(db_file)
cursor = cnx.cursor()
p,e,c,ce,ec,s,sc,es,esc,cnt = (0,)*10
cursor.execute("select mtype || \" \" || message from statistics_messages where mtype='HELO_INFO' order by rtime desc limit %d"%tries)
tries = 0
for (rec,) in cursor:
plain_text = rec.encode("utf8")
enc_data = str(gpg.encrypt(plain_text, public_key, always_trust=True))
enc_data_comp = zlib.compress(enc_data)
comp_data = zlib.compress(plain_text)
comp_data_enc = str(gpg.encrypt(comp_data, public_key, always_trust=True))
sign_data = str(gpg.sign(plain_text))
sign_data_comp = zlib.compress(sign_data)
sign_enc_data = str(gpg.encrypt(plain_text, public_key, sign=public_key, always_trust=True))
sign_enc_data_comp = zlib.compress(sign_enc_data)
p+=len(plain_text)
e+=len(enc_data)
c+=len(comp_data)
ce+=len(comp_data_enc)
ec+=len(enc_data_comp)
s+=len(sign_data)
sc+=len(sign_data_comp)
es+=len(sign_enc_data)
esc+=len(sign_enc_data_comp)
if len(enc_data_comp)<len(enc_data):
示例2: GPGMail
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import sign [as 别名]
class GPGMail(object):
def __init__(self, gpg=None):
if gpg:
self.gpg = gpg
else:
self.gpg = GPG(gpgbinary="gpg2", use_agent=True)
GPGLogger.setLevel(logging.DEBUG)
self.logger = logging.getLogger('GPGMail')
def _armor(self, container, message, signature):
"""
Make the armor signed message
"""
if container.get_param('protocol') == 'application/pgp-signature':
m = re.match(r'^pgp-(.*)$', container.get_param('micalg'))
if m:
TEMPLATE = '-----BEGIN PGP SIGNED MESSAGE-----\n' \
'Hash: %s\n\n' \
'%s\n%s\n'
s = StringIO()
text = re.sub(r'(?m)^(-.*)$', r'- \1', self._flatten(message))
s.write(TEMPLATE % (m.group(1).upper(),
text,
signature.get_payload()))
return s.getvalue()
return None
def _filter_parts(sefl, m, f):
"""Iterate over messages that satisfy predicate."""
for x in m.walk():
if f(x):
yield x
def _flatten(self, message):
"""Return raw string representation of message."""
try:
s = StringIO()
g = Generator(s, mangle_from_=False, maxheaderlen=0)
g.flatten(message)
return s.getvalue()
finally:
s.close()
def _signed_parts(self, message):
"""Iterate over signed parts of message yielding
GPG verification status and signed contents."""
f = lambda m: \
m.is_multipart() and m.get_content_type() == 'multipart/signed' \
or not m.is_multipart() and m.get_content_maintype() == 'text'
for part in self._filter_parts(message, f):
if part.is_multipart():
try:
signed_part, signature = part.get_payload()
s = None
sign_type = signature.get_content_type()
if sign_type == 'application/pgp-signature':
s = self._armor(part, signed_part, signature)
yield self.gpg.verify(s), True, signature.get_filename()
except ValueError:
pass
else:
payload = part.get_payload(decode=True)
yield self.gpg.verify(payload), False, None
def verify(self, message):
"""Verify signature of a email message and returns the GPG info"""
result = {}
for verified, sign_attached, filename in self._signed_parts(message):
if verified is not None:
result = verified.__dict__
break
if 'status' in result and result['status'] is None:
return None
if 'gpg' in result:
del(result['gpg'])
if sign_attached:
result['filename'] = filename
return result
def _get_digest_algo(self, signature):
"""
Returns a string representation of the digest algo used in signature.
Raises a TypeError if signature.hash_algo does not exists.
Acceptable values for signature.hash_algo are:
MD5 1
SHA1 2
RMD160 3
SHA256 8
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import sign [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
示例4: GnuPGMessage
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import sign [as 别名]
class GnuPGMessage(EmailMessage):
def __init__(self, *args, **kwargs):
super(GnuPGMessage, self).__init__(*args, **kwargs)
self.gpg = GPG(gnupghome=settings.GNUPG_HOMEDIR)
def _normalize(self, original):
return "\r\n".join(str(original).splitlines()[1:]) + "\r\n"
def _sign(self, original):
sig = self.gpg.sign(
self._normalize(original), detach=True, clearsign=False)
signature = MIMEApplication(
str(sig), 'pgp-signature', encode_noop, name='signature.asc')
signature.add_header('Content-Description', 'Digital signature')
del signature['MIME-Version']
return signature
def message(self):
encoding = self.encoding or settings.DEFAULT_CHARSET
msg = MIMEUTF8QPText(self.body, encoding)
msg = self._create_message(msg)
msg['Subject'] = self.subject
msg['From'] = self.extra_headers.get('From', self.from_email)
msg['To'] = self.extra_headers.get('To', ', '.join(self.to))
if self.cc:
msg['Cc'] = ', '.join(self.cc)
header_names = [key.lower() for key in self.extra_headers]
if 'date' not in header_names:
msg['Date'] = formatdate()
if 'message-id' not in header_names:
msg['Message-ID'] = make_msgid()
for name, value in self.extra_headers.items():
if name.lower() in ('from', 'to'):
# From and To are already handled
continue
msg[name] = value
del msg['MIME-Version']
wrapper = SafeMIMEMultipart(
'signed', protocol='application/pgp-signature',
micalg='pgp-sha512')
wrapper.preamble = (
"This is an OpenPGP/MIME signed message (RFC 4880 and 3156)"
)
# copy headers from original message to PGP/MIME envelope
for header in msg.keys():
if header.lower() not in (
'content-disposition', 'content-type', 'mime-version'
):
for value in msg.get_all(header):
wrapper.add_header(header, value)
del msg[header]
for part in msg.walk():
del part['MIME-Version']
signature = self._sign(msg)
wrapper['Content-Disposition'] = 'inline'
wrapper.attach(msg)
wrapper.attach(signature)
return wrapper