本文整理汇总了Python中gnupg.GPG.encrypt方法的典型用法代码示例。如果您正苦于以下问题:Python GPG.encrypt方法的具体用法?Python GPG.encrypt怎么用?Python GPG.encrypt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gnupg.GPG
的用法示例。
在下文中一共展示了GPG.encrypt方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reqPGP
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
class reqPGP(object):
def __init__(self, path=None):
self.gpg = GPG(gpgbinary=('../gpg.exe' if osName == 'nt' else 'gpg'))
if not path:
try:
self.path = environ["HOME"] + '/'
except KeyError:
self.path = environ["HOMEPATH"] + '\\'
else:
if path[-1] != '\\' and osName == 'nt':
path += '\\'
elif path[-1] != '/' and osName == 'posix':
path += '/'
self.path = path
def genKey(self, account, passphrase):
input_data = self.gpg.gen_key_input(
name_email=account,
passphrase=passphrase)
self.gpg.gen_key(input_data)
def encryptFile(self, account, data):
encryptedData = str(self.gpg.encrypt(data, account))
with open(self.path + '.' + account + '.req', 'w') as f:
f.write(encryptedData)
def decryptFile(self, account, passphrase):
with open(self.path + '.' + account + '.req', 'rb') as f:
decryptedData = str(self.gpg.decrypt_file(f, passphrase=passphrase))
return decryptedData
def deleteKey(self, keyId):
self.gpg.delete_keys(keyId, True)
self.gpg.delete_keys(keyId)
示例2: send_mail
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
def send_mail(subject, body_text, addr_from, addr_to, fail_silently=False,
attachments=None, body_html=None):
"""
Sends a multipart email containing text and html versions which
are encrypted for each recipient that has a valid gpg key
installed.
"""
# Allow for a single address to be passed in.
if not hasattr(addr_to, "__iter__"):
addr_to = [addr_to]
# Obtain a list of the recipients that have gpg keys installed.
valid_key_addresses = []
if USE_GNUPG:
queryset = Address.objects.filter(address__in=addr_to)
valid_key_addresses = queryset.values_list("address", flat=True)
# Create the gpg object.
if valid_key_addresses:
gpg = GPG(gnupghome=GNUPG_HOME)
gpg_kwargs = {}
if ALWAYS_TRUST:
gpg_kwargs.update({'always_trust':ALWAYS_TRUST})
# Encrypts body if recipient has a gpg key installed.
encrypt_if_key = lambda body, addr: (body if addr not in valid_key_addresses
else unicode(gpg.encrypt(body, addr, **gpg_kwargs)))
# Load attachments and create name/data tuples.
attachments_parts = []
if attachments is not None:
for attachment in attachments:
with open(attachment, "rb") as f:
attachments_parts.append((basename(attachment), f.read()))
# Send emails.
for addr in addr_to:
msg = EmailMultiAlternatives(subject, encrypt_if_key(body_text, addr),
addr_from, [addr])
if body_html is not None:
msg.attach_alternative(encrypt_if_key(body_html, addr), "text/html")
for parts in attachments_parts:
msg.attach(parts[0]+'.asc' if ADD_EXTENSION else parts[0], encrypt_if_key(parts[1], addr))
msg.send(fail_silently=fail_silently)
示例3: write_key
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
def write_key(path, key_data, gpg_bin, gpg_opts):
"""Encrypt and write a single key file.
:param str path: The path to the key to decrypt.
:param str gpg_bin: The path to the gpg binary.
:param list gpg_opts: The options for gpg.
"""
gpg = GPG(gpgbinary=gpg_bin, options=gpg_opts)
gpg_recipients = _get_gpg_recipients(path)
# pass always ends it's files with an endline
if not key_data.endswith('\n'):
key_data += '\n'
key_data_enc = gpg.encrypt(key_data, gpg_recipients).data
with open(path, 'wb') as key_file:
key_file.write(key_data_enc)
示例4: Vault
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
class Vault(object):
def __init__(self):
self.vault = {}
self._gpg = GPG()
self._file_descriptor = None
self.passphrase = None
def reload(self):
if None in (self._file_descriptor, self.passphrase):
raise RuntimeError('Cannot reload before calling .load()')
self.load(self._file_descriptor, self.passphrase)
def load(self, file_descriptor, passphrase):
self._file_descriptor = file_descriptor
self.passphrase = passphrase
self._file_descriptor.seek(0)
json_ = self._gpg.decrypt_file(self._file_descriptor, passphrase=self.passphrase)
self.vault = json.loads(str(json_))
def save(self, file_descriptor=None, passphrase=None):
if file_descriptor is not None:
self._file_descriptor = file_descriptor
if passphrase is not None:
self.passphrase = passphrase
self._file_descriptor.seek(0)
json_ = json.dumps(self.vault)
encrypted = self._gpg.encrypt(json_, False, passphrase=self.passphrase, symmetric=True)
self._file_descriptor.write(str(encrypted))
def __getitem__(self, key):
return self.vault[key]
def get(self, name, default=None):
return self.vault.get(name, default)
def __setitem__(self, key, value):
self.vault[key] = value
def __delitem__(self, key):
del self._vault[key]
def list(self):
return sorted(self._vault.keys())
示例5: _encrypt
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
def _encrypt(self, plain):
# test if we have public keys for all recipients
available_recipients = []
keys = []
for key in Key.objects.all():
keys.append(key)
available_recipients.extend(key.addresses.split(', '))
logger.debug("available_recipients: %s", available_recipients)
if not all(recipient in available_recipients for recipient in self.recipients()):
logger.error("Public key not present for at least one of these recipients: %s", self.recipients())
raise GPGException("Public key not present for at least one recipient")
# encryption
with TemporaryDirectory() as temp_dir:
gpg = GPG(gnupghome=temp_dir)
for key in keys:
gpg.import_keys(key.key)
res = gpg.encrypt(plain, self.recipients(), always_trust=True)
if not res:
handle_gpg_error(res, 'encryption')
return smart_text(res)
示例6: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
#.........这里部分代码省略.........
PNs = 0
ratchet_flag = True
else: # bob mode
RK = pbkdf2(mkey, b'\x00', 10, prf='hmac-sha256')
HKs = pbkdf2(mkey, b'\x02', 10, prf='hmac-sha256')
HKr = None
NHKs = pbkdf2(mkey, b'\x04', 10, prf='hmac-sha256')
NHKr = pbkdf2(mkey, b'\x03', 10, prf='hmac-sha256')
CKs = pbkdf2(mkey, b'\x06', 10, prf='hmac-sha256')
CKr = None
DHRs_priv = self.state['DHRs_priv']
DHRs = self.state['DHRs']
DHRr = None
CONVid = pbkdf2(mkey, b'\x07', 10, prf='hmac-sha256')
Ns = 0
Nr = 0
PNs = 0
ratchet_flag = False
DHIr = other_identityKey
self.state = \
{'name': self.name, 'other_name': other_name, 'RK': RK,
'HKs': HKs, 'HKr': HKr, 'NHKs': NHKs, 'NHKr': NHKr, 'CKs': CKs,
'CKr': CKr, 'DHIs_priv': self.state['DHIs_priv'],
'DHIs': self.state['DHIs'], 'DHIr': DHIr,
'DHRs_priv': DHRs_priv, 'DHRs': DHRs, 'DHRr': DHRr,
'CONVid': CONVid, 'Ns': Ns, 'Nr': Nr, 'PNs': PNs,
'ratchet_flag': ratchet_flag,
}
self.ratchetKey = False
self.ratchetPKey = False
def encrypt(self, plaintext):
if self.state['ratchet_flag']:
self.state['DHRs_priv'], self.state['DHRs'] = self.genKey()
self.state['HKs'] = self.state['NHKs']
self.state['RK'] = sha256(self.state['RK'] +
self.gen_dh(
self.state['DHRs_priv'],
self.state['DHRr'])).digest()
if self.mode:
self.state['NHKs'] = pbkdf2(self.state['RK'], b'\x03', 10,
prf='hmac-sha256')
self.state['CKs'] = pbkdf2(self.state['RK'], b'\x05', 10,
prf='hmac-sha256')
else:
self.state['NHKs'] = pbkdf2(self.state['RK'], b'\x04', 10,
prf='hmac-sha256')
self.state['CKs'] = pbkdf2(self.state['RK'], b'\x06', 10,
prf='hmac-sha256')
self.state['PNs'] = self.state['Ns']
self.state['Ns'] = 0
self.state['ratchet_flag'] = False
mk = sha256(self.state['CKs'] + '0').digest()
msg1 = self.enc(self.state['HKs'], str(self.state['Ns']).zfill(3) +
str(self.state['PNs']).zfill(3) + self.state['DHRs'])
msg2 = self.enc(mk, plaintext)
pad_length = 106 - len(msg1)
pad = os.urandom(pad_length - 1) + chr(pad_length)
msg = msg1 + pad + msg2
self.state['Ns'] += 1
self.state['CKs'] = sha256(self.state['CKs'] + '1').digest()
return msg
def commit_skipped_mk(self):
示例7: vote
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
def vote(request, poll_id):
if not request.user.is_authenticated():
return HttpResponseRedirect("/")
else:
logged_in = True
error = ""
success = ""
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
username = request.user.username
if (
(not poll.is_allowed_voter(username))
or poll.has_voted(username)
or (poll.starts > datetime.datetime.now())
or (poll.ends < datetime.datetime.now())
):
return HttpResponseRedirect("/mypolls")
poll_choices = Choice.objects.filter(poll=poll).order_by("id")
choice_type = "radio"
if poll.max_choices > 1:
choice_type = "checkbox"
vote_tag = ""
vote_receipt_encrypted = ""
if request.POST:
form = Form(request.POST)
if form.is_valid():
choices = request.POST.getlist("choices")
# Check that the submitted choices exist and belong to the poll
for choice in choices:
try:
c = Choice.objects.get(pk=choice, poll=poll)
except Choice.DoesNotExist:
error = "The submitted choices are not valid choices of the poll"
# Check that the submitted choices are between min and max number of choices allowed for the poll
if len(choices) > poll.max_choices:
error = "You cannot vote for more than " + str(poll.max_choices) + " choices"
if len(choices) < poll.min_choices:
error = "You must vote for at least " + str(poll.min_choices) + " choices"
if poll.max_choices == 1: # a better error message for single choice polls
error = "You must select a choice"
if list_has_duplicates(choices):
error = "Each choice can be selected only once"
if not error:
# Construct a unique, random string to use as a vote tag
while not vote_tag:
vote_tag = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(35))
try:
v = Vote.objects.get(tag=vote_tag)
vote_tag = ""
except Vote.DoesNotExist: # our random string is unique so we can use it as a vote tag
# Encrypt the vote tag with user's public pgp key and sign it with the key of the system authority
gpg = GPG(gpgbinary=settings.GNUPGBINARY, gnupghome=settings.GNUPGHOME)
vote_receipt = """GPGVote: Vote Receipt
---------------------
You are voter:
%s
You voted for Poll:
\'%s\'
Created by:
%s
Your Vote Tag is: %s
You made the following choices:""" % (
request.user.pgpkey.name + " <" + request.user.username + ">",
poll.question,
poll.creator.pgpkey.name + " <" + poll.creator.username + ">",
vote_tag,
)
for choice in choices:
choice = Choice.objects.get(pk=choice, poll=poll)
vote_receipt = vote_receipt + "\n * %s" % choice.choice
vote_receipt_encrypted = gpg.encrypt(
vote_receipt,
request.user.pgpkey.fingerprint,
always_trust=True,
sign=settings.SYSTEM_KEY_FINGERPRINT,
passphrase=settings.SYSTEM_KEY_PASSWD,
)
# Create the actual vote records in database
for choice in choices:
vote = Vote(choice=Choice.objects.get(id=choice), tag=vote_tag)
vote.save()
poll.add_voter(voter=username, To="who_voted")
poll.save()
#.........这里部分代码省略.........
示例8: GPG
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
gpg = GPG(gnupghome='.python-gnupg')
gpg.encoding = 'utf-8'
# These commands needed to be run once to generate and save the key
#input_data = gpg.gen_key_input(key_type="RSA", key_length=2**KEY_EXP)
#gpg_key = gpg.gen_key(input_data)
# BEGIN BLOCK CIPHER OPERATIONS
set_run = ['block']
setup = """\
from __main__ import gpg, message, enctext
"""
# Create cipher, create cipher text for decryption, time operations, update
# result with each new operation
algo_run = ['3DES']
enctext = gpg.encrypt(message, None, symmetric='3DES',
passphrase=PASSPHRASE, armor=False)
enc_run = ['encrypt']
enc_trial = Timer(
"gpg.encrypt(message, None, symmetric='3DES', passphrase=PASSPHRASE, armor=False)",
setup)
enc_run.append(enc_trial.repeat(RUN_COUNT, 1))
algo_run.append(enc_run)
dec_run = ['decrypt']
dec_trial = Timer(
"gpg.decrypt(enctext.data, passphrase=PASSPHRASE)",
setup)
dec_run.append(dec_trial.repeat(RUN_COUNT, 1))
algo_run.append(dec_run)
set_run.append(algo_run)
# Create cipher, create cipher text for decryption, time operations, update
示例9: getCoreLogger
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
getCoreLogger().exception("GPG not working: "+str(e))
sys.exit(1)
db_file = os.path.join(get_settings().get_main_config_dir(),"lunchinator.sq3")
tries = 10
public_key = "0x17F57DC2"
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)
示例10: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [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
示例11: PGPContext
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [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)
示例12: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
#.........这里部分代码省略.........
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
encrypt_obj = self.gpgh.encrypt_file(filestream, str(self.receiver_desc['gpg_key_fingerprint']))
if not encrypt_obj.ok:
# continue here if is not ok
log.err("Falure in encrypting file %s %s (%s)" % ( plainpath,
self.receiver_desc['username'], self.receiver_desc['gpg_key_fingerprint']) )
log.err(encrypt_obj.stderr)
raise errors.GPGKeyInvalid
log.debug("Encrypting for %s (%s) file %s (%d bytes)" %
(self.receiver_desc['username'], self.receiver_desc['gpg_key_fingerprint'],
plainpath, len(str(encrypt_obj))) )
encrypted_path = os.path.join( os.path.abspath(output_path),
"gpg_encrypted-%d-%d" %
(random.randint(0, 0xFFFF), random.randint(0, 0xFFFF)))
if os.path.isfile(encrypted_path):
log.err("Unexpected unpredictable unbelievable error! %s" % encrypted_path)
raise errors.InternalServerError("File conflict in GPG encrypted output")
try:
with open(encrypted_path, "w+") as f:
f.write(str(encrypt_obj))
示例13: GLBPGP
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [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))
#.........这里部分代码省略.........
示例14: GPG
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt [as 别名]
gpg = GPG(binary='/usr/bin/gpg2',
homedir='~/.gnupg',
keyring='pubring.gpg',
secring='secring.gpg')
stored_keys = gpg.list_keys()
message = "This is a test message to be encripted."
options_enc = {
'passphrase': passphrase,
'armor': True,
'default_key': gpg_test_fingerprint
}
encrypted_msg = gpg.encrypt(message, gpg_test_fingerprint, **options_enc)
print(encrypted_msg)
options_dec = {
'passphrase': passphrase
}
decrypted_msg = gpg.decrypt(str(encrypted_msg), **options_dec)
assert message == str(decrypted_msg)
print("This is the original message:", decrypted_msg)
''' "Valid" will return a boolean saying whether the decrypted message's
signature is valid.'''
assert decrypted_msg.valid