本文整理汇总了Python中gnupg.GPG类的典型用法代码示例。如果您正苦于以下问题:Python GPG类的具体用法?Python GPG怎么用?Python GPG使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GPG类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_empty_config
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
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: do_job_unit
def do_job_unit(self, event, corpus, unit, **kwargs):
preroll = kwargs.get("preroll", 0)
for i, (domain, count, path, url) in enumerate(self.get_chunk_info_paths_urls(
event, corpus, preroll=preroll)):
if i != unit:
continue
gpg = GPG()
#http = urllib3.PoolManager()
parent = os.path.dirname(path)
if not os.path.exists(parent):
try:
os.makedirs(parent)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(parent):
pass
retries = 3
while 1:
try:
r = requests.get(url, timeout=30)
with open(path, u'wb') as f:
f.write(str(gpg.decrypt(r.content)))
break
except requests.exceptions.ConnectionError:
retries -= 1
if retries == 0:
break
except urllib3.exceptions.ReadTimeoutError:
retries -= 1
if retries == 0:
break
示例4: get_expirations
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: decrypt
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'
示例6: getGPG
def getGPG():
global lunch_gpg
if not lunch_gpg:
from gnupg import GPG
gbinary = getBinary("gpg", "bin")
if not gbinary:
raise Exception("GPG not found")
ghome = os.path.join(get_settings().get_main_config_dir(),"gnupg")
if not locale.getpreferredencoding():
# Fix for GnuPG on Mac
# TODO will this work on systems without English locale?
os.putenv("LANG", "en_US.UTF-8")
if not locale.getpreferredencoding():
# Fix for GnuPG on Mac
# TODO will this work on systems without English locale?
os.putenv("LANG", "en_US.UTF-8")
try:
if getPlatform() == PLATFORM_WINDOWS:
lunch_gpg = GPG("\""+gbinary+"\"",ghome)
else:
lunch_gpg = GPG(gbinary,ghome)
if not lunch_gpg.encoding:
lunch_gpg.encoding = 'utf-8'
except Exception, e:
raise Exception("GPG not working: "+str(e))
示例7: _get_gpg_output_for_pubkey_file
def _get_gpg_output_for_pubkey_file(self, pubkey_file):
with TemporaryDirectory() as temp_gpg_home:
gpg = GPG(gnupghome=temp_gpg_home)
with open(pubkey_file, 'rb') as pubkey_fh:
gpg.import_keys(pubkey_fh.read())
gpg_stdout = check_output([
'gpg',
'--homedir', temp_gpg_home,
'--keyid-format', '0xlong',
'--with-fingerprint',
'--list-options', 'show-uid-validity',
'--verify-options', 'show-uid-validity',
# '--list-sigs',
# Public keys for signatures over the UIDs might not be present.
'--list-public-keys'
]).decode('utf-8')
truncated_lines = []
in_header = True
for line in gpg_stdout.split('\n'):
# OpenPGP subkeys might be subject to more frequent change
# and are expected to not always be updated in the keyring.
# You might need to update OpenPGP subkeys from keyservers.
if not in_header and not re.match(r'sub\s', line):
truncated_lines.append(line)
if re.match(r'^---------', line):
in_header = False
return '\n'.join(truncated_lines)
示例8: test_addresses_for_key
def test_addresses_for_key(self):
"""Test email address extraction from GPG public keys."""
with TemporaryDirectory() as temp_dir:
gpg_keychain = GPG(gnupghome=temp_dir)
res = gpg_keychain.import_keys(self.key.key)
self.assertTrue(res)
self.assertEqual(len(res.results), 1)
self.assertEqual(addresses_for_key(gpg_keychain, res.results[0]), ['[email protected]'])
示例9: clean
def clean(self):
gpg = GPG(gpgbinary=settings.GNUPGBINARY, gnupghome=settings.GNUPGHOME)
key = gpg.get_key(self.fingerprint)
if key['ownertrust'] in settings.TRUST_LEVELS:
self.is_trusted = True
else:
self.is_trusted = False
self.save()
示例10: clean_key
def clean_key(self):
"""
Validate the key contains an email address.
"""
key = self.cleaned_data["key"]
gpg = GPG(gnupghome=GNUPG_HOME)
result = gpg.import_keys(key)
if result.count == 0:
raise forms.ValidationError(_("Invalid Key"))
return key
示例11: sign
def sign(self, dist):
self._reprepro('export %s' % dist)
gpg = GPG()
filename = os.path.join(self.path, 'dists/%s/Release' % dist)
detach_file = filename + '.gpg'
try:
os.unlink(detach_file)
except: pass
result = gpg.sign_file(file(filename, 'r'), keyid=conf('repository.signkey'), outputfile=detach_file)
示例12: reqPGP
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)
示例13: extract_content
def extract_content(path, keyring, output_dir, output_ext):
""" Use the keyring to decrypt a document """
name = os.path.splitext(os.path.basename(path))[0]
gpg = GPG(gnupghome=keyring)
new_path = os.path.join(output_dir, '.'.join([name, output_ext]))
try:
with open(path, 'rb') as content:
data = gpg.decrypt(content.read(), output=new_path)
except OSError:
raise DecryptionError("Could not open '%s'" % path, path)
return new_path
示例14: forward_change
def forward_change(apps, schema_editor):
Key = apps.get_model('email_extras', 'Key')
Address = apps.get_model('email_extras', 'Address')
for key in Key.objects.all():
addresses = Address.objects.filter(address__in=key.addresses.split(','))
addresses.update(key=key)
gpg = GPG(gnupghome=GNUPG_HOME)
result = gpg.import_keys(key.key)
key.fingerprint = result.fingerprints[0]
key.save()
示例15: _generate_key
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']