Export GPG public key for specified `user_id`.
169180
def export_public_key(user_id, env=None, sp=subprocess):
    """"""
    args = gpg_command(['--export', user_id])
    result = check_output(args=args, env=env, sp=sp)
    if not result:
        log.error('could not find public key %r in local GPG keyring', user_id)
        raise KeyError(user_id)
    return result
609280
def from_keybase(username):
    """"""
    public_key = key_from_keybase(username)
    fingerprint = public_key['fingerprint'][-8:].upper().encode('ascii')
    key = public_key['bundle'].encode('ascii')
    if not has_gpg_key(fingerprint):
        LOG.debug("Importing gpg key for %s", username)
        if not import_gpg_key(key):
            raise aomi.exceptions.KeybaseAPI("import key for %s" % username)

    return fingerprint
1176940
def get_keygrip(user_id, sp=subprocess):
    """"""
    args = gpg_command(['--list-keys', '--with-keygrip', user_id])
    output = check_output(args=args, sp=sp).decode('utf-8')
    return re.findall(r'Keygrip = (\w+)', output)[0]
34087
def gpg_verify( path_to_verify, sigdata, sender_key_info, config_dir=None ):
    

    if config_dir is None:
        config_dir = get_config_dir()

    # ingest keys 
    tmpdir = make_gpg_tmphome( prefix="verify", config_dir=config_dir )
    res = gpg_stash_key( "verify", sender_key_info['key_data'], config_dir=config_dir, gpghome=tmpdir )
    if res is None:
        shutil.rmtree(tmpdir)
        return {'error': 'Failed to stash key %s' % sender_key_info['key_id']}

    # stash detached signature 
    fd, path = tempfile.mkstemp( prefix=".sig-verify-" )
    f = os.fdopen(fd, "w")
    f.write( sigdata )
    f.flush()
    os.fsync(f.fileno())
    f.close()

    # verify 
    gpg = gnupg.GPG( homedir=tmpdir )

    with open(path, "r") as fd_in:
        res = gpg.verify_file( fd_in, data_filename=path_to_verify )

    shutil.rmtree(tmpdir)
    try:
        os.unlink(path)
    except:
        pass

    if not res:
        log.debug("verify_file error: %s" % res.__dict__)
        return {'error': 'Failed to decrypt data'}

    log.debug("verification succeeded from keys in %s" % config_dir)
    return {'status': True}
649176
def fingerprint2keyid(fingerprint):
    """"""

    if gnupg is None:
        return

    gpg = gnupg.GPG()
    private_keys = gpg.list_keys(True)

    keyid = None
    for private_key in private_keys:
        if private_key['fingerprint'] == config["gpg_key_fingerprint"]:
            keyid = private_key['keyid']
            break

    return keyid
903582
private function key_generate()
    {
        // Crypt_GPG does not support key generation for multiple identities
        // It is also very slow (which is problematic because it may exceed
        // request time limit) and requires entropy generator
        // That's why we use only OpenPGP.js method of key generation
        return;

        $user = rcube_utils::get_input_value('_user', rcube_utils::INPUT_POST, true);
        $pass = rcube_utils::get_input_value('_password', rcube_utils::INPUT_POST, true);
        $size = (int) rcube_utils::get_input_value('_size', rcube_utils::INPUT_POST);

        if ($size > 4096) {
            $size = 4096;
        }

        $ident = rcube_mime::decode_address_list($user, 1, false);

        if (empty($ident)) {
            $this->rc->output->show_message('enigma.keygenerateerror', 'error');
            $this->rc->output->send();
        }

        $this->enigma->load_engine();
        $result = $this->enigma->engine->generate_key(array(
            'user'     => $ident[1]['name'],
            'email'    => $ident[1]['mailto'],
            'password' => $pass,
            'size'     => $size,
        ));

        if ($result instanceof enigma_key) {
            $this->rc->output->command('enigma_key_create_success');
            $this->rc->output->show_message('enigma.keygeneratesuccess', 'confirmation');
        }
        else {
            $this->rc->output->show_message('enigma.keygenerateerror', 'error');
        }

        $this->rc->output->send();
    }
870129
def fingerprint_from_file(filename):
    """"""
    cmd = flatten([gnupg_bin(), gnupg_home(), filename])
    outp = stderr_output(cmd).split('\n')
    if not outp[0].startswith('pub'):
        raise CryptoritoError('probably an invalid gpg key')

    return outp[1].strip()
849589
def have_key(self, *keygrips):
        """"""
        for keygrip in keygrips:
            try:
                self.get_identity(keygrip=keygrip)
                break
            except KeyError as e:
                log.warning('HAVEKEY(%s) failed: %s', keygrip, e)
        else:
            raise AgentError(b'ERR 67108881 No secret key <GPG Agent>')
221815
def gpg_download_key( key_id, key_server, config_dir=None ):
    

    config_dir = get_config_dir( config_dir )
    tmpdir = make_gpg_tmphome( prefix="download", config_dir=config_dir )
    gpg = gnupg.GPG( homedir=tmpdir )
    recvdat = gpg.recv_keys( key_server, key_id )
    fingerprint = None

    try:
        assert recvdat.count == 1
        assert len(recvdat.fingerprints) == 1
        fingerprint = recvdat.fingerprints[0]

    except AssertionError, e:
        log.exception(e)
        log.error( "Failed to fetch key '%s' from '%s'" % (key_id, key_server))
        shutil.rmtree( tmpdir )
        return None

    keydat = gpg.export_keys( [fingerprint] )
    shutil.rmtree( tmpdir )
    return str(keydat)
921219
public function userKey($user_id, $key_id)
    {
        return $this->get('users/'.$this->encodePath($user_id).'/keys/'.$this->encodePath($key_id));
    }
970872
def export_public_key(vk, label):
    
    key_type, blob = serialize_verifying_key(vk)
    log.debug('fingerprint: %s', fingerprint(blob))
    b64 = base64.b64encode(blob).decode('ascii')
    return u'{} {} {}\n'.format(key_type.decode('ascii'), b64, label)
438909
def FromPublicKey(cls, public_key):
    """"""
    # Our CN will be the first 64 bits of the hash of the public key
    # in MPI format - the length of the key in 4 bytes + the key
    # prefixed with a 0. This weird format is an artifact from the way
    # M2Crypto handled this, we have to live with it for now.
    n = public_key.GetN()
    raw_n = binascii.unhexlify("%x" % n)

    mpi_format = struct.pack(">i", len(raw_n) + 1) + b"\x00" + raw_n

    digest = binascii.hexlify(hashlib.sha256(mpi_format).digest()[:8])
    return cls("C.{}".format(digest.decode("ascii")))
1156263
def get_public_key(self):
        """"""
        return PublicKey.from_verifying_key(
            self._private_key.get_verifying_key(),
            network=self.network, compressed=self.compressed)
715629
def pubkey(self, identity, ecdh=False):
        """"""
        _verify_support(identity)
        data = self.vk.to_string()
        x, y = data[:32], data[32:]
        prefix = bytearray([2 + (bytearray(y)[0] & 1)])
        return bytes(prefix) + x
760267
def from_passwd(uid_min=None, uid_max=None):
        """"""
        import pwd
        users = Users(oktypes=User)
        passwd_list = pwd.getpwall()
        if not uid_min:
            uid_min = UID_MIN
        if not uid_max:
            uid_max = UID_MAX
        sudoers_entries = read_sudoers()
        for pwd_entry in passwd_list:
            if uid_min <= pwd_entry.pw_uid <= uid_max:
                user = User(name=text_type(pwd_entry.pw_name),
                            passwd=text_type(pwd_entry.pw_passwd),
                            uid=pwd_entry.pw_uid,
                            gid=pwd_entry.pw_gid,
                            gecos=text_type(pwd_entry.pw_gecos),
                            home_dir=text_type(pwd_entry.pw_dir),
                            shell=text_type(pwd_entry.pw_shell),
                            public_keys=read_authorized_keys(username=pwd_entry.pw_name),
                            sudoers_entry=get_sudoers_entry(username=pwd_entry.pw_name,
                                                            sudoers_entries=sudoers_entries))
                users.append(user)
        return users
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
581090
def get_fingerprint_from_public_key(pubkey):
    

    # TODO: why is there a tmpdir?
    with tempdir() as workdir:
        key = os.path.join(workdir, 'key.pub')
        with open(key, 'w') as fd:
            fd.write(pubkey)

        cmd = [
            'ssh-keygen',
            '-l',
            '-f', key,
        ]

        p = Subprocess(cmd)
        output = p.stdout.strip()
        bits, fingerprint, _ = output.split(' ', 2)
        return fingerprint