本文整理汇总了Python中gnupg.GPG.encrypt_file方法的典型用法代码示例。如果您正苦于以下问题:Python GPG.encrypt_file方法的具体用法?Python GPG.encrypt_file怎么用?Python GPG.encrypt_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gnupg.GPG
的用法示例。
在下文中一共展示了GPG.encrypt_file方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encrypt
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt_file [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'
示例2: createciphermsgs_gpg
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt_file [as 别名]
def createciphermsgs_gpg(jt65msgcount, stegmsg, recipient, verbose=False):
# Performs the actual GPG encryption
ciphermsgs = []
while len(stegmsg) % 8:
stegmsg += " "
gpg = GPG()
stegstream = io.StringIO(unicode(stegmsg))
cipherdata = gpg.encrypt_file(stegstream, recipient)
if cipherdata == "":
print "You must set the recipient's trust level to -something- in your keyring before we can encrypt the message"
sys.exit(0)
cipherlist = list(bytearray(str(cipherdata)))
if verbose:
print "Cipher list: " + str(cipherlist)
if jt65msgcount * 8 < len(cipherlist):
print(
"Length of hidden message exceeds capacity of number of valid JT65 messages provided")
sys.exit(0)
# Is the total length too big to fit into our max number of packets?
if len(cipherlist) > MAX_MULTI_PACKET_STEG_BYTES_GPG:
print("Length of hidden message exceeds capacity of multi-packet steg")
sys.exit(0)
totalpackets = len(cipherlist) / 8
createciphermsgs_packer_other(
totalpackets, ciphermsgs, cipherlist, verbose)
return ciphermsgs
示例3: PGPContext
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt_file [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)
示例4: __init__
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt_file [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))
示例5: GLBPGP
# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import encrypt_file [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))
#.........这里部分代码省略.........