Create a gpg object given a gpg_keydir, and then use it to try to decrypt
    the data to be rendered.
776831
def render(gpg_data, saltenv='base', sls='', argline='', **kwargs):
    '''
    
    '''
    if not _get_gpg_exec():
        raise SaltRenderError('GPG unavailable')
    log.debug('Reading GPG keys from: %s', _get_key_dir())

    translate_newlines = kwargs.get('translate_newlines', False)
    return _decrypt_object(gpg_data, translate_newlines=translate_newlines)
130420
private static Object createKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
        Class keyGenClass = lookupKeyGenClass();
        Object keypair = ClassUtil.newInstance(keyGenClass, "RSA", "SHA1WithRSA");
        ClassUtil.applyMethod(keypair, "generate", 2048);
        return keypair;
    }
1358306
private void createKeysIfNotExist() {
        if (!keyPairExists()) {
            try {
                final KeyPair keyPair = generateKeyPair();
                save(keyPair);
            } catch (NoSuchAlgorithmException e) {
                LOGGER.error("An error occurred generating new keypair");
                LOGGER.error(e.getMessage());
            } catch (IOException e) {
                LOGGER.error("An error occurred saving newly generated keypair");
                LOGGER.error(e.getMessage());
            }
        }
        if (!secretKeyExists()) {
            try {
                final SecretKey secretKey = generateSecretKey();
                save(secretKey);
            } catch (NoSuchAlgorithmException e) {
                LOGGER.error("An error occurred generating new secret key");
                LOGGER.error(e.getMessage());
            } catch (IOException e) {
                LOGGER.error("An error occurred saving newly generated secret key");
                LOGGER.error(e.getMessage());
            }
        }
    }
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
1117387
def __generate_key(self, config):
        
        cwd = config.get('ssh_path', self._install_directory())
        if config.is_affirmative('create', default="yes"):
            if not os.path.exists(cwd):
                os.makedirs(cwd)
            if not os.path.exists(os.path.join(cwd, config.get('keyname'))):
                command = "ssh-keygen -t %(type)s -f %(keyname)s -N  " % config.to_dict()
                lib.call(command, cwd=cwd, output_log_level=logging.DEBUG)
        if not config.has('ssh_path'):
            config.set('ssh_path', cwd)
        config.set('ssh_key_path', os.path.join(config.get('ssh_path'), config.get('keyname')))
874590
def stderr_with_input(cmd, stdin):
    """"""
    handle, gpg_stderr = stderr_handle()
    LOGGER.debug("GPG command %s", ' '.join(cmd))
    try:
        gpg_proc = subprocess.Popen(cmd,  # nosec
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE,
                                    stderr=gpg_stderr)

        output, _err = gpg_proc.communicate(polite_bytes(stdin))

        if handle:
            handle.close()

        return output
    except subprocess.CalledProcessError as exception:
        return gpg_error(exception, 'GPG variable encryption error')
    except OSError as exception:
        raise CryptoritoError("File %s not found" % exception.filename)
228309
def _decrypt_object(obj):
    '''
    
    '''
    if isinstance(obj, six.string_types):
        return _fetch_secret(obj)
    elif isinstance(obj, dict):
        for pass_key, pass_path in six.iteritems(obj):
            obj[pass_key] = _decrypt_object(pass_path)
    elif isinstance(obj, list):
        for pass_key, pass_path in enumerate(obj):
            obj[pass_key] = _decrypt_object(pass_path)
    return obj
33448
def gen_key(minion_id, dns_name=None, password=None, key_len=2048):
    '''
    
    '''
    keygen_type = 'RSA'

    if keygen_type == "RSA":
        if HAS_M2:
            gen = RSA.gen_key(key_len, 65537)
            private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
        else:
            gen = RSA.generate(bits=key_len)
            private_key = gen.exportKey('PEM', password)
        if dns_name is not None:
            bank = 'digicert/domains'
            cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
            try:
                data = cache.fetch(bank, dns_name)
                data['private_key'] = private_key
                data['minion_id'] = minion_id
            except TypeError:
                data = {'private_key': private_key,
                        'minion_id': minion_id}
            cache.store(bank, dns_name, data)
    return private_key
1000228
def decrypt(data, key):
    ''''''
    data_len = len(data)
    data = ffi.from_buffer(data)
    key = ffi.from_buffer(__tobytes(key))
    out_len = ffi.new('size_t *')
    result = lib.xxtea_decrypt(data, data_len, key, out_len)
    ret = ffi.buffer(result, out_len[0])[:]
    lib.free(result)
    return ret
1019784
def create_key_pair(self, cert_type, bits):
        

        pkey = crypto.PKey()
        pkey.generate_key(cert_type, bits)
        return pkey
215082
def import_key(keyid):
    
    try:
        return fetch_import_key(keyid)
    except GPGKeyError as e:
        error_out("Could not import key: {}".format(str(e)))
1324316
def do_thing():
    """"""
    if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
        encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
    elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
        decrypt_file(sys.argv[2], sys.argv[3])
    elif len(sys.argv) == 3 and sys.argv[1] == "encrypt":
        encrypt_var(sys.argv[2])
    elif len(sys.argv) == 2 and sys.argv[1] == "decrypt":
        decrypt_var()
    elif len(sys.argv) == 3 and sys.argv[1] == "decrypt":
        decrypt_var(passphrase=sys.argv[2])
    elif len(sys.argv) == 3 and sys.argv[1] == "has_key":
        has_key(sys.argv[2])
    elif len(sys.argv) == 3 and sys.argv[1] == "import_keybase":
        import_keybase(sys.argv[2])
    elif len(sys.argv) == 3 and sys.argv[1] == "export":
        export_key(sys.argv[2])
    else:
        print("Cryptorito testing wrapper. Not suitable for routine use.",
              file=sys.stderr)
        sys.exit(1)
11276
def export_public_key(device_type, args):
    """"""
    log.warning('NOTE: in order to re-generate the exact same GPG key later, '
                'run this command with "--time=%d" commandline flag (to set '
                'the timestamp of the GPG key manually).', args.time)
    c = client.Client(device=device_type())
    identity = client.create_identity(user_id=args.user_id,
                                      curve_name=args.ecdsa_curve)
    verifying_key = c.pubkey(identity=identity, ecdh=False)
    decryption_key = c.pubkey(identity=identity, ecdh=True)
    signer_func = functools.partial(c.sign, identity=identity)

    if args.subkey:  # add as subkey
        log.info('adding %s GPG subkey for "%s" to existing key',
                 args.ecdsa_curve, args.user_id)
        # subkey for signing
        signing_key = protocol.PublicKey(
            curve_name=args.ecdsa_curve, created=args.time,
            verifying_key=verifying_key, ecdh=False)
        # subkey for encryption
        encryption_key = protocol.PublicKey(
            curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
            created=args.time, verifying_key=decryption_key, ecdh=True)
        primary_bytes = keyring.export_public_key(args.user_id)
        result = encode.create_subkey(primary_bytes=primary_bytes,
                                      subkey=signing_key,
                                      signer_func=signer_func)
        result = encode.create_subkey(primary_bytes=result,
                                      subkey=encryption_key,
                                      signer_func=signer_func)
    else:  # add as primary
        log.info('creating new %s GPG primary key for "%s"',
                 args.ecdsa_curve, args.user_id)
        # primary key for signing
        primary = protocol.PublicKey(
            curve_name=args.ecdsa_curve, created=args.time,
            verifying_key=verifying_key, ecdh=False)
        # subkey for encryption
        subkey = protocol.PublicKey(
            curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
            created=args.time, verifying_key=decryption_key, ecdh=True)

        result = encode.create_primary(user_id=args.user_id,
                                       pubkey=primary,
                                       signer_func=signer_func)
        result = encode.create_subkey(primary_bytes=result,
                                      subkey=subkey,
                                      signer_func=signer_func)

    return protocol.armor(result, 'PUBLIC KEY BLOCK')
277484
def make_gpg_home(appname, config_dir=None):
    

    assert is_valid_appname(appname)
    config_dir = get_config_dir( config_dir )
    path = os.path.join( config_dir, "gpgkeys", appname )

    if not os.path.exists(path):
        os.makedirs( path, 0700 )
    else:
        os.chmod( path, 0700 )

    return path
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}
1079775
def fingerprint_from_var(var):
    """"""
    vsn = gpg_version()
    cmd = flatten([gnupg_bin(), gnupg_home()])
    if vsn[0] >= 2 and vsn[1] < 1:
        cmd.append("--with-fingerprint")

    output = polite_string(stderr_with_input(cmd, var)).split('\n')
    if not output[0].startswith('pub'):
        raise CryptoritoError('probably an invalid gpg key')

    if vsn[0] >= 2 and vsn[1] < 1:
        return output[1] \
            .split('=')[1] \
            .replace(' ', '')

    return output[1].strip()
955211
def _create_trustdb(cls):
    """"""
    trustdb = os.path.join(cls.homedir, 'trustdb.gpg')
    if not os.path.isfile(trustdb):
        log.info("GnuPG complained that your trustdb file was missing. %s"
                 % "This is likely due to changing to a new homedir.")
        log.info("Creating trustdb.gpg file in your GnuPG homedir.")
        cls.fix_trustdb(trustdb)