当前位置: 首页>>代码示例>>Python>>正文


Python gnupg.GPG类代码示例

本文整理汇总了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()
开发者ID:glasserc,项目名称:tuyau,代码行数:7,代码来源:main.py

示例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'
开发者ID:niklasad1,项目名称:crypt,代码行数:35,代码来源:crypt.py

示例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
开发者ID:kedz,项目名称:cuttsum,代码行数:34,代码来源:trecdata.py

示例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
开发者ID:rowanthorpe,项目名称:GLBackend,代码行数:33,代码来源:security.py

示例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'
开发者ID:niklasad1,项目名称:crypt,代码行数:31,代码来源:crypt.py

示例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))
开发者ID:hannesrauhe,项目名称:lunchinator,代码行数:29,代码来源:utilities.py

示例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)
开发者ID:debops,项目名称:debops-keyring,代码行数:28,代码来源:keyring.py

示例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]'])
开发者ID:Strassengezwitscher,项目名称:Strassengezwitscher,代码行数:8,代码来源:test_utils.py

示例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()
开发者ID:DzorD,项目名称:gpgvote,代码行数:8,代码来源:models.py

示例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
开发者ID:Deliverability,项目名称:django-email-extras,代码行数:10,代码来源:forms.py

示例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)
开发者ID:simplegeo,项目名称:repoman,代码行数:10,代码来源:repository.py

示例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)
开发者ID:simonvadee,项目名称:requireris,代码行数:35,代码来源:reqPGP.py

示例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
开发者ID:Outernet-Project,项目名称:artexin,代码行数:11,代码来源:content_crypto.py

示例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()
开发者ID:stephenmcd,项目名称:django-email-extras,代码行数:12,代码来源:0003_auto_20161103_0315.py

示例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']
开发者ID:adlnet,项目名称:LR-Lite,代码行数:12,代码来源:models.py


注:本文中的gnupg.GPG类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。