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


Python GPG.import_keys方法代码示例

本文整理汇总了Python中gnupg.GPG.import_keys方法的典型用法代码示例。如果您正苦于以下问题:Python GPG.import_keys方法的具体用法?Python GPG.import_keys怎么用?Python GPG.import_keys使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gnupg.GPG的用法示例。


在下文中一共展示了GPG.import_keys方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_expirations

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
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,代码行数:35,代码来源:security.py

示例2: _get_gpg_output_for_pubkey_file

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
    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,代码行数:30,代码来源:keyring.py

示例3: test_addresses_for_key

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
 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,代码行数:10,代码来源:test_utils.py

示例4: clean_key

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
 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,代码行数:12,代码来源:forms.py

示例5: forward_change

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
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,代码行数:14,代码来源:0003_auto_20161103_0315.py

示例6: save

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
 def save(self, *args, **kwargs):
     super(Key, self).save(*args, **kwargs)
     gpg = GPG(gnupghome=GNUPG_HOME)
     result = gpg.import_keys(self.key)
     addresses = []
     for key in result.results:
         addresses.extend(addresses_for_key(gpg, key))
     self.addresses = ",".join(addresses)
     for address in addresses:
         address, _ = Address.objects.get_or_create(address=address)
         address.use_asc = self.use_asc
         address.save()
开发者ID:jlachowski,项目名称:django-email-extras,代码行数:14,代码来源:models.py

示例7: _encrypt

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [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)
开发者ID:Strassengezwitscher,项目名称:Strassengezwitscher,代码行数:24,代码来源:mail.py

示例8: import_key

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
def import_key(keypath, keyring):
    """ Imports all keys from specified directory
    This function is idempotent, so importing the same key multiple times will
    always succeed.
    :param keypath:     path to armored key file
    :param keyring:     directory of the keyring
    """
    gpg = GPG(gnupghome=keyring)
    try:
        with open(keypath, 'r') as keyfile:
            result = gpg.import_keys(keyfile.read())
    except OSError:
        raise KeyImportError("Could not open '%s'" % keypath, keypath)
    if result.count == 0:
        raise KeyImportError("Could not import '%s'" % keypath, keypath)
开发者ID:Outernet-Project,项目名称:artexin,代码行数:17,代码来源:content_crypto.py

示例9: save

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
 def save(self, *args, **kwargs):
     with TemporaryDirectory() as temp_dir:
         gpg_keychain = GPG(gnupghome=temp_dir)
         res = gpg_keychain.import_keys(self.key)
         if not res:
             handle_gpg_error(res, 'import')
         if len(gpg_keychain.list_keys(True)) > 0:
             raise GPGException("Will not import GPG private key!")
         addresses = []
         for key in res.results:
             addresses.extend(addresses_for_key(gpg_keychain, key))
         self.addresses = ', '.join(addresses)
     operation = "Updating" if self.pk else "Creating"
     logger.info("%s GPG key for: %s", operation, self.addresses)
     super(Key, self).save(*args, **kwargs)
开发者ID:Strassengezwitscher,项目名称:Strassengezwitscher,代码行数:17,代码来源:models.py

示例10: save_model

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
        def save_model(self, request, obj, form, change):
            """
			import the key and parse the addresses from it and save them
			and omit the super save_model call so as to never save the key instance
			"""
            gpg = GPG(gnupghome=GNUPG_HOME)
            result = gpg.import_keys(obj.key)
            if result.count == 0:
                raise forms.ValidationError("Invalid Key")
            else:
                addresses = []
                for key in result.results:
                    addresses.extend(addresses_for_key(gpg, key))
                obj.addresses = ",".join(addresses)
                for address in addresses:
                    Address.objects.get_or_create(address=address)
开发者ID:wiremine,项目名称:django-email-extras,代码行数:18,代码来源:admin.py

示例11: clean_key

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
    def clean_key(self):
        """
        Raises ValidationError if the entered key is invalid or includes a GPG private key.
        """
        data = self.cleaned_data['key']
        with TemporaryDirectory() as temp_dir:
            gpg_keychain = GPG(gnupghome=temp_dir)
            res = gpg_keychain.import_keys(data)
            if not res:
                errors = [forms.ValidationError(_("Invalid key."), code='invalid')]
                for attr in ['status', 'stderr']:  # not all fields are always present
                    if hasattr(res, attr):
                        errors.append(forms.ValidationError("%(name)s: %(value)s",
                                                            params={'name': attr, 'value': getattr(res, attr)},
                                                            code=attr))
                raise forms.ValidationError(errors)

            if len(gpg_keychain.list_keys(True)) > 0:  # check existance of private keys
                raise forms.ValidationError(_("Import public keys only, no private keys! "
                                              "You should consider the private key(s) compromised."),
                                            code='private_key')
        return data
开发者ID:Strassengezwitscher,项目名称:Strassengezwitscher,代码行数:24,代码来源:admin.py

示例12: TempGPGWrapper

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
class TempGPGWrapper(object):
    """
    A context manager that wraps a temporary GPG keyring which only contains
    the keys given at object creation.
    """

    def __init__(self, keys=None, gpgbinary=None):
        """
        Create an empty temporary keyring and import any given C{keys} into
        it.

        :param keys: OpenPGP key, or list of.
        :type keys: OpenPGPKey or list of OpenPGPKeys
        :param gpgbinary: Name for GnuPG binary executable.
        :type gpgbinary: C{str}
        """
        self._gpg = None
        self._gpgbinary = gpgbinary
        if not keys:
            keys = list()
        if not isinstance(keys, list):
            keys = [keys]
        self._keys = keys
        for key in keys:
            leap_assert_type(key, OpenPGPKey)

    def __enter__(self):
        """
        Build and return a GPG keyring containing the keys given on
        object creation.

        :return: A GPG instance containing the keys given on object creation.
        :rtype: gnupg.GPG
        """
        self._build_keyring()
        return self._gpg

    def __exit__(self, exc_type, exc_value, traceback):
        """
        Ensure the gpg is properly destroyed.
        """
        # TODO handle exceptions and log here
        self._destroy_keyring()

    def _build_keyring(self):
        """
        Create a GPG keyring containing the keys given on object creation.

        :return: A GPG instance containing the keys given on object creation.
        :rtype: gnupg.GPG
        """
        privkeys = [key for key in self._keys if key and key.private is True]
        publkeys = [key for key in self._keys if key and key.private is False]
        # here we filter out public keys that have a correspondent
        # private key in the list because the private key_data by
        # itself is enough to also have the public key in the keyring,
        # and we want to count the keys afterwards.

        privfps = map(lambda privkey: privkey.fingerprint, privkeys)
        publkeys = filter(
            lambda pubkey: pubkey.fingerprint not in privfps, publkeys)

        listkeys = lambda: self._gpg.list_keys()
        listsecretkeys = lambda: self._gpg.list_keys(secret=True)

        self._gpg = GPG(binary=self._gpgbinary,
                        homedir=tempfile.mkdtemp())
        leap_assert(len(listkeys()) is 0, 'Keyring not empty.')

        # import keys into the keyring:
        # concatenating ascii-armored keys, which is correctly
        # understood by GPG.

        self._gpg.import_keys("".join(
            [x.key_data for x in publkeys + privkeys]))

        # assert the number of keys in the keyring
        leap_assert(
            len(listkeys()) == len(publkeys) + len(privkeys),
            'Wrong number of public keys in keyring: %d, should be %d)' %
            (len(listkeys()), len(publkeys) + len(privkeys)))
        leap_assert(
            len(listsecretkeys()) == len(privkeys),
            'Wrong number of private keys in keyring: %d, should be %d)' %
            (len(listsecretkeys()), len(privkeys)))

    def _destroy_keyring(self):
        """
        Securely erase the keyring.
        """
        # TODO: implement some kind of wiping of data or a more
        # secure way that
        # does not write to disk.

        try:
            for secret in [True, False]:
                for key in self._gpg.list_keys(secret=secret):
                    self._gpg.delete_keys(
                        key['fingerprint'],
                        secret=secret)
#.........这里部分代码省略.........
开发者ID:elijh,项目名称:keymanager,代码行数:103,代码来源:openpgp.py

示例13: import_from_dump

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
def import_from_dump(file):
    """Import from an SKS dump."""
    # First, load a new GPG instance.
    gpg = GPG(gnupghome="/tmp/skier-import")

    # Read data in
    dumpf = open(file, 'rb')
    data = dumpf.read()
    dump = pgpdump.BinaryData(data)
    dumpf.close()

    # Import the keydump into gpg
    try:
        gpg.import_keys(data)
    except:
        # Yeah, whatever.
        pass
    """
    # Read in packets
    packets_flat = []
    try:
        for packet in dump.packets():
            packets_flat.append(packet)
    except Exception as e:
        # Some SKS data is malformed.
        print("SKS data in {} is malformed - truncating at packet {}".format(file, len(packets_flat)+1))

    # Unflatten list into sublists, starting at each new Publickey packet.
    packets = []
    tmpl = []
    for packet in packets_flat:
        if isinstance(packet, pgpdump.packet.PublicKeyPacket) and not isinstance(packet, pgpdump.packet.PublicSubkeyPacket) and tmpl:
            tmpl.insert(0, packet)
            gpg_output = gpg.export_keys(keyids=[packet.fingerprint.decode()])
            if gpg_output:
                tmpl.append(gpg_output)
            packets.append(tmpl)
            tmpl = []
            continue
        else:
            tmpl.append(packet)
    packets.append(tmpl)
    """
    armored = []
    for key in gpg.list_keys():
        tmpkey = gpg.export_keys(keyids=key['fingerprint'])
        if not tmpkey:
            print("{} is malformed - not importing".format(key['fingerprint']))
        armored.append(tmpkey)


    print("Importing {} keys".format(len(armored)))
    """
    for gpack in packets:
        keyinfo = KeyInfo.pgp_dump(None, packets=gpack)
        dbob = db.Key.from_keyinfo(keyinfo)
        db.db.session.add(dbob)

    db.db.session.commit()
    """

    for key in armored:
        kyinfo = KeyInfo.pgp_dump(key)
        if not kyinfo.fingerprint:
            print("Key {} is malformed - cannot be imported".format(kyinfo))
        else:
            dbob = db.Key.from_keyinfo(kyinfo)
            db.db.session.add(dbob)

    db.db.session.commit()

    shutil.rmtree("/tmp/skier-import")
开发者ID:grocid,项目名称:Skier,代码行数:74,代码来源:manager.py

示例14: PGPContext

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [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)
开发者ID:chojar,项目名称:GlobaLeaks,代码行数:85,代码来源:pgp.py

示例15: check_git_commits

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import import_keys [as 别名]
    def check_git_commits(self, repo_path='.'):
        with TemporaryDirectory() as temp_gpg_home:
            gpg = GPG(gnupghome=temp_gpg_home)

            for long_key_id in os.listdir(self._keyring_name):
                with open(os.path.join(
                    self._keyring_name,
                    long_key_id
                ), 'rb') as pubkey_fh:
                    gpg.import_keys(pubkey_fh.read())

            repo = git.Git(repo_path)
            repo.update_environment(GNUPGHOME=temp_gpg_home)
            commit_count = 0
            # %G?: show "G" for a Good signature,
            #           "B" for a Bad signature,
            #           "U" for a good, untrusted signature and
            #           "N" for no signature
            # TODO 'N' is also returned for signatures made by expired subkeys.
            # Seems to be a bug.
            # Current workaround is only to check the HEAD commit.
            for log_line in [repo.log('--format=%H %G?').split('\n')[0]]:
                (commit_hash, signature_check) = log_line.split(' ')
                commit_count += 1
                if signature_check not in ['U', 'G']:
                    raise Exception(
                        "OpenPGP signature of commit could not be verified."
                        "\nAffected commit:\n{}".format(
                            repo.log('-1', commit_hash),
                        )
                    )
            logging.info(
                textwrap.dedent(
                    """
                    OK - All commits in the repository '{repo_path}' are signed
                    and all public keys to verify the signatures are contained
                    in current HEAD of this repository.
                    """
                ).lstrip().replace('\n', ' ').format(
                    repo_path=repo_path,
                )
            )
            if commit_count <= 0:
                # That condition is expected to never be True because of
                # "returned with exit code 128" for "fatal: bad default revision 'HEAD'".
                # Leaving it in just to be sure (in case git becomes more
                # "friendly" in the future.
                raise Exception(
                    "Expected at least one git commit."
                    " Found {} commits.".format(
                        commit_count,
                    )
                )
            else:
                logging.info(
                    "OK - The repository '{repo_path}' contains at least one commit.".format(
                        repo_path=repo_path,
                    )
                )

        return True
开发者ID:debops,项目名称:debops-keyring,代码行数:63,代码来源:keyring.py


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