Exports a GPG key and returns it
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')
214364
def addresses_for_key(gpg, key):
    
    fingerprint = key["fingerprint"]
    addresses = []
    for key in gpg.list_keys():
        if key["fingerprint"] == fingerprint:
            addresses.extend([address.split("<")[-1].strip(">")
                              for address in key["uids"] if address])
    return addresses
39765
public function import(string $gpgKey): string
    {
        try {
            $gnupg = new \Crypt_GPG($this->options);
            /** @var array<string, string> $data */
            $data = $gnupg->importKey($gpgKey);

            return $data['fingerprint'];
        } catch (\PEAR_Exception $ex) {
            throw new GPGMailerException(
                'Could not import public key: ' . $ex->getMessage(),
                $ex->getCode(),
                $ex
            );
        }
    }
215082
def import_key(keyid):
    
    try:
        return fetch_import_key(keyid)
    except GPGKeyError as e:
        error_out("Could not import key: {}".format(str(e)))
371735
def gen_keys(keysize=2048):
    '''
    
    '''
    # Mandate that keys are at least 2048 in size
    if keysize < 2048:
        keysize = 2048
    tdir = tempfile.mkdtemp()

    salt.crypt.gen_keys(tdir, 'minion', keysize)
    priv_path = os.path.join(tdir, 'minion.pem')
    pub_path = os.path.join(tdir, 'minion.pub')
    with salt.utils.files.fopen(priv_path) as fp_:
        priv = salt.utils.stringutils.to_unicode(fp_.read())
    with salt.utils.files.fopen(pub_path) as fp_:
        pub = salt.utils.stringutils.to_unicode(fp_.read())
    shutil.rmtree(tdir)
    return priv, pub
636059
def clean_key(self):
        
        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
1175621
def import_keybase(useropt):
    """"""
    public_key = None
    u_bits = useropt.split(':')
    username = u_bits[0]
    if len(u_bits) == 1:
        public_key = cryptorito.key_from_keybase(username)
    else:
        fingerprint = u_bits[1]
        public_key = cryptorito.key_from_keybase(username, fingerprint)

    if cryptorito.has_gpg_key(public_key['fingerprint']):
        sys.exit(2)

    cryptorito.import_gpg_key(public_key['bundle'].encode('ascii'))
    sys.exit(0)
344649
def gpg_encrypt( fd_in, path_out, sender_key_info, recipient_key_infos, passphrase=None, config_dir=None ):
    

    if config_dir is None:
        config_dir = get_config_dir()

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

    # copy over our key
    try:
        sender_privkey = gpg_export_key( sender_key_info['app_name'], sender_key_info['key_id'], include_private=True, config_dir=config_dir )
    except Exception, e:
        log.exception(e)
        shutil.rmtree(tmpdir)
        return {'error': 'No such private key'}

    res = gpg_stash_key( "encrypt", sender_privkey, config_dir=config_dir, gpghome=tmpdir )
    if res is None:
        shutil.rmtree(tmpdir)
        return {'error': 'Failed to load sender private key'}

    recipient_key_ids = [r['key_id'] for r in recipient_key_infos]

    # do the encryption
    gpg = gnupg.GPG( homedir=tmpdir )
    res = gpg.encrypt_file( fd_in, recipient_key_ids, sign=sender_key_info['key_id'], passphrase=passphrase, output=path_out, always_trust=True )
    shutil.rmtree(tmpdir)

    if res.status != 'encryption ok':
        log.debug("encrypt_file error: %s" % res.__dict__)
        log.debug("recipients: %s" % recipient_key_ids)
        log.debug("signer: %s" % sender_key_info['key_id'])
        return {'error': 'Failed to encrypt data'}
    
    return {'status': True}
243464
def import_keys(keydata)
      err = GPGME::gpgme_op_import(self, keydata)
      exc = GPGME::error_to_exception(err)
      raise exc if exc
    end
55632
def derive_key(seed_key, seed_rand, rounds, password=None, keyfile=None):
    
    if password == '': password = None
    if keyfile == '': keyfile = None
    if password is None and keyfile is None:
        raise ValueError("Password and/or keyfile is required.")
        
    if password is None:
        masterkey = key_from_keyfile(keyfile)
    elif password and keyfile:
        passwordkey = key_from_password(password)
        filekey = key_from_keyfile(keyfile)
        sha = SHA256.new()
        sha.update(passwordkey + filekey)
        masterkey = sha.digest()
    else:
        masterkey = key_from_password(password)

    # Create the key that is needed to...
    final_key = transform_key(masterkey, seed_key=seed_key, seed_rand=seed_rand, rounds=rounds)
    
    return final_key
999798
def get_gnupg_components(sp=subprocess):
    """"""
    args = [util.which('gpgconf'), '--list-components']
    output = check_output(args=args, sp=sp)
    components = dict(re.findall('(.*):.*:(.*)', output.decode('utf-8')))
    log.debug('gpgconf --list-components: %s', components)
    return components
1118057
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))
1156492
def _get_pkey(self):
        """"""
        keypath = self.config.server["pkey"]
        with open(os.path.expanduser(keypath)) as f:
            pkey = paramiko.RSAKey.from_private_key(f)

        return pkey
75403
def import_gpg_key(key):
    """"""
    if not key:
        raise CryptoritoError('Invalid GPG Key')

    key_fd, key_filename = mkstemp("cryptorito-gpg-import")
    key_handle = os.fdopen(key_fd, 'w')

    key_handle.write(polite_string(key))
    key_handle.close()
    cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename])
    output = stderr_output(cmd)
    msg = 'gpg: Total number processed: 1'
    output_bits = polite_string(output).split('\n')
    return len([line for line in output_bits if line == msg]) == 1
144316
def _list_keys(user=None, gnupghome=None, secret=False):
    '''
    
    '''
    gpg = _create_gpg(user, gnupghome)
    _keys = gpg.list_keys(secret)
    return _keys
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