Displays gpg key choice and returns key
358108
def choose_key(gpg_private_keys):
    """"""

    uid_strings_fp = []
    uid_string_fp2key = {}

    current_key_index = None

    for i, key in enumerate(gpg_private_keys):
        fingerprint = key['fingerprint']

        if fingerprint == config["gpg_key_fingerprint"]:
            current_key_index = i

        for uid_string in key['uids']:
            uid_string_fp = '"' + uid_string + ' (' + fingerprint + ')'
            uid_strings_fp.append(uid_string_fp)
            uid_string_fp2key[uid_string_fp] = key

    msg = _('Choose a GPG key for signing pyspread save files.\n'
            'The GPG key must not have a passphrase set.')

    dlg = wx.SingleChoiceDialog(None, msg, _('Choose key'), uid_strings_fp,
                                wx.CHOICEDLG_STYLE)

    childlist = list(dlg.GetChildren())
    childlist[-3].SetLabel(_("Use chosen key"))
    childlist[-2].SetLabel(_("Create new key"))

    if current_key_index is not None:
        # Set choice to current key
        dlg.SetSelection(current_key_index)

    if dlg.ShowModal() == wx.ID_OK:
        uid_string_fp = dlg.GetStringSelection()
        key = uid_string_fp2key[uid_string_fp]

    else:
        key = None

    dlg.Destroy()

    return key
762186
def export_gpg_key(key):
    """"""
    cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
                   "--export", key])
    handle, gpg_stderr = stderr_handle()
    try:
        gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,  # nosec
                                    stderr=gpg_stderr)
        output, _err = gpg_proc.communicate()
        if handle:
            handle.close()

        return portable_b64encode(output)
    except subprocess.CalledProcessError as exception:
        LOGGER.debug("GPG Command %s", ' '.join(exception.cmd))
        LOGGER.debug("GPG Output %s", exception.output)
        raise CryptoritoError('GPG encryption error')
1251482
def sign(filename):
    """"""

    if gnupg is None:
        return

    gpg = gnupg.GPG()

    with open(filename, "rb") as signfile:
        keyid = fingerprint2keyid(config["gpg_key_fingerprint"])

        if keyid is None:
            msg = "No private key for GPG fingerprint '{}'."
            raise ValueError(msg.format(config["gpg_key_fingerprint"]))

        signed_data = gpg.sign_file(signfile, keyid=keyid, detach=True)

    return signed_data
1230417
def gpg_verify_key( key_id, key_data, config_dir=None ):
    

    key_data = str(key_data)

    config_dir = get_config_dir( config_dir )
    sanitized_key_id = "".join( key_id.upper().split(" ") )
    
    if len(sanitized_key_id) < 16:
        log.debug("Fingerprint is too short to be secure")
        return False

    fingerprint = gpg_key_fingerprint( key_data, config_dir=config_dir )
    if fingerprint is None:
        log.debug("Failed to fingerprint key")
        return False

    if sanitized_key_id != fingerprint and not fingerprint.endswith( sanitized_key_id ):
        log.debug("Imported key does not match the given ID")
        return False

    else:
        return True
219108
def get_keypair(vm_):
    '''
    
    '''
    keypair = config.get_cloud_config_value('keypair', vm_, __opts__)

    if keypair:
        return keypair
    else:
        return False
691235
def gpg_list_app_keys( blockchain_id, appname, proxy=None, wallet_keys=None, config_dir=None ):
    

    raise Exception("BROKEN; depends on list_mutable_data")

    assert is_valid_appname(appname)

    config_dir = get_config_dir( config_dir )
    client_config_path = os.path.join(config_dir, blockstack_client.CONFIG_FILENAME )

    if proxy is None:
        proxy = blockstack_client.get_default_proxy( config_path=client_config_path )

    key_info = []
    key_prefix = "gpg.%s." % appname

    # immutable data key listing (look for keys that start with 'appname:')
    immutable_listing = list_immutable_data( blockchain_id, proxy=proxy )
    if 'error' in immutable_listing:
        raise Exception("Blockstack error: %s" % immutable_listing['error'])

    for immutable in immutable_listing['data']:
        name = immutable['data_id']
        data_hash = immutable['hash']
        if name.startswith( key_prefix ):
            key_info.append( {
                'keyName': name[len(key_prefix):],
                'contentUrl': make_immutable_data_url( blockchain_id, name, data_hash )
            })

    # mutable data key listing (look for keys that start with 'appname:')
    # TODO: use 'accounts'
    mutable_listing = list_mutable_data( blockchain_id, proxy=proxy, wallet_keys=wallet_keys )
    if 'error' in mutable_listing:
        raise Exception("Blockstack error: %s" % mutable_listing['error'])

    for mutable in mutable_listing['data']:
        name = mutable['data_id']
        version = mutable['version']
        if name.startswith( key_prefix ):
            key_info.append( {
                'keyName': name[len(key_prefix):],
                'contentUrl': make_mutable_data_url( blockchain_id, name, version )
            })

    return key_info
200510
def addresses_for_key(gpg, key):
    
    return [address.split("<")[-1].strip(">")
            for address in gpg.list_keys().key_map[key['fingerprint']]["uids"]
            if address]
1063873
def exportNewKey(fingerprint):
    
    log.info("Exporting key: %s" % fingerprint)

    keyfn = os.path.join(gpg.homedir,
                         fingerprint + '-8192-bit-key') + os.path.extsep

    pubkey = gpg.export_keys(fingerprint)
    seckey = gpg.export_keys(fingerprint, secret=True)
    subkey = gpg.export_keys(fingerprint, secret=True, subkeys=True)

    with open(keyfn + 'pub' + os.path.extsep + 'asc', 'w') as fh:
        fh.write(pubkey)
    with open(keyfn + 'sec' + os.path.extsep + 'asc', 'w') as fh:
        fh.write(seckey)
    with open(keyfn + 'sub' + os.path.extsep + 'asc', 'w') as fh:
        fh.write(subkey)
1361835
def init_gpg(self):
        
        if self.gpg_verify:
            logger.debug("gpg verification enabled, initializing gpg")
            gpg_home = os.path.expanduser('~/.gnupg')
            self.gpg = gnupg.GPG(gnupghome=gpg_home)
            self.key_path, self.key_info = self.get_signing_key()
            logger.debug("{0} {1}".format(self.key_path, self.key_info))
            self.check_signing_key()
338784
def keypath(self, key):
        
        return fs.path(self.path, self.escape_key(key))
172686
def __key(self):
        

        return (self.latex_name, self.arguments, self.options,
                self.extra_arguments)
981588
def gpg_interactive_input(self, sub_keys_number):
        
        deselect_sub_key = "key 0\n"

        _input = self._main_key_command()
        for sub_key_number in range(1, sub_keys_number + 1):
            _input += self._sub_key_command(sub_key_number) + deselect_sub_key
        return "%ssave\n" % _input
93255
def __get_keys(self, name='master', passphrase=None):
        '''
        
        '''
        path = os.path.join(self.opts['pki_dir'],
                            name + '.pem')
        if not os.path.exists(path):
            log.info('Generating %s keys: %s', name, self.opts['pki_dir'])
            gen_keys(self.opts['pki_dir'],
                     name,
                     self.opts['keysize'],
                     self.opts.get('user'),
                     passphrase)
        if HAS_M2:
            key_error = RSA.RSAError
        else:
            key_error = ValueError
        try:
            key = get_rsa_key(path, passphrase)
        except key_error as e:
            message = 'Unable to read key: {0}; passphrase may be incorrect'.format(path)
            log.error(message)
            raise MasterExit(message)
        log.debug('Loaded %s key: %s', name, path)
        return key
208137
def check_key(self, key):
        """"""
        return _check_key(key, allow_unicode_keys=self.allow_unicode_keys,
                          key_prefix=self.key_prefix)
1156336
def _key_from_req(req):
    """"""
    if hasattr(req, 'key'):
        # from pkg_resources, such as installed dists for pip-sync
        key = req.key
    else:
        # from packaging, such as install requirements from requirements.txt
        key = req.name

    key = key.replace('_', '-').lower()
    return key
973265
def gpg_key(value):
    
    try:
        return crypto.get_key(value)
    except GPGProblem as e:
        raise ValidateError(str(e))
951132
def gpg_command(args, env=None):
    """"""
    if env is None:
        env = os.environ
    cmd = get_gnupg_binary(neopg_binary=env.get('NEOPG_BINARY'))
    return [cmd] + args