Encrypt a stream of data for a set of keys.
    @sender_key_info should be a dict with
    {
        'key_id': ...
        'key_data': ...
        'app_name'; ...
    }
    Return {'status': True} on success
    Return {'error': ...} on error
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}
794030
def decrypt(self, senderKeyMessageBytes):
        
        try:
            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)
            if record.isEmpty():
                raise NoSessionException("No sender key for: %s" % self.senderKeyName)
            senderKeyMessage = SenderKeyMessage(serialized = bytes(senderKeyMessageBytes))
            senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId())

            senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic())

            senderKey = self.getSenderKey(senderKeyState, senderKeyMessage.getIteration())

            plaintext = self.getPlainText(senderKey.getIv(), senderKey.getCipherKey(), senderKeyMessage.getCipherText())

            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)

            return plaintext
        except (InvalidKeyException, InvalidKeyIdException) as e:
            raise InvalidMessageException(e)
64425
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['data'] = u(array.get('data'))
        data['hash'] = u(array.get('hash'))
        data['secret'] = u(array.get('secret'))
        data['_raw'] = array
        return EncryptedCredentials(**data)
369841
def encrypt(self, serialized):
        

        fernet = Fernet(self.encryption_cipher_key)
        return fernet.encrypt(serialized)
1194319
def decode!
            self.decrypt! if self.is_a?(Encryption::EncryptedStream)
            return if decoded?

            filters = self.filters
            dparams = decode_params

            @data = @encoded_data.dup
            @data.freeze

            filters.each_with_index do |filter, layer|
                params = dparams[layer].is_a?(Dictionary) ? dparams[layer] : {}

                # Handle Crypt filters.
                if filter == :Crypt
                    raise Filter::Error, "Crypt filter must be the first filter" unless layer.zero?

                    # Skip the Crypt filter.
                    next
                end

                begin
                    @data = decode_data(@data, filter, params)
                rescue Filter::Error => error
                    @data = error.decoded_data
                    raise
                end
            end

            self
        end
440132
def _plaintext_data_key():
    '''
    
    '''
    response = getattr(_plaintext_data_key, 'response', None)
    cache_hit = response is not None
    if not cache_hit:
        response = _api_decrypt()
        setattr(_plaintext_data_key, 'response', response)
    key_id = response['KeyId']
    plaintext = response['Plaintext']
    if hasattr(plaintext, 'encode'):
        plaintext = plaintext.encode(__salt_system_encoding__)
    log.debug('Using key %s from %s', key_id, 'cache' if cache_hit else 'api call')
    return plaintext
1111024
public static byte[] encrypt(byte[] data, byte[] key) {
        checkNotNull(data);
        checkNotNull(key);
        checkArgument(key.length >= 5 && key.length <= 256);
        StreamCipher rc4 = new RC4Engine();
        rc4.init(true, new KeyParameter(key));
        byte[] encrypted = new byte[data.length];
        rc4.processBytes(data, 0, data.length, encrypted, 0);
        return encrypted;
    }
232255
def encode_metadata(self):
        
        encoded_list = []
        for key, value in iteritems(self.metadata):
            key_str = str(key)  # dict keys may be of any object type.

            # confirm that the key does not contain unwanted characters.
            if re.search(r'^$|[\s,]+', key_str):
                msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.'
                raise ValueError(msg.format(key_str))

            value_bytes = b(value)  # python 3 only encodes bytes
            encoded_list.append('{} {}'.format(key_str, b64encode(value_bytes).decode('ascii')))
        return encoded_list
386317
def encrypt(message, key: nil)

      raise ArgumentError.new('The message argument is required.') if message.blank?
      raise ArgumentError.new('The key argument is required.')     if key.blank?

      cipher = OpenSSL::Cipher::AES.new(256, 'CBC')
      cipher.encrypt
      cipher.padding = aes_256_padding
      cipher.key     = key

      cipher.update(message)+cipher.final

    end
188085
def decrypt(data, key)
			if data == nil
				return nil
			end
			iv = data[0..15]
			payload = data[16..-1]
			cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
			cipher.padding = 0
			cipher.key = Base64.strict_decode64(key);
			cipher.iv = iv
			decrypted = cipher.update(payload);
			decrypted << cipher.final();
			return decrypted
		end
1294110
def dict(self):
        

        d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs if p.key not in ('data')}

        d['secret'] = 'not available'

        if self.secret_password:
            try:
                d['secret'] = self.decrypt_secret()
            except AccountDecryptionError:
                pass

        if self.data:
            for k, v in self.data.items():
                d[k] = v

        return {k: v for k, v in d.items()}
209516
def secret_merge(self, secure_data_path, key):
        """"""
        get_resp = get_with_retry(self.cerberus_url + '/v1/secret/' + secure_data_path, headers=self.HEADERS)
        temp_key = {}
        # Ignore a return of 404 since it means the key might not exist
        if get_resp.status_code == requests.codes.bad and get_resp.status_code not in [403, 404]:
            throw_if_bad_response(get_resp)
        elif get_resp.status_code in [403, 404]:
            temp_key = {}
        else:
            temp_key = get_resp.json()['data']
        # Allow key to be either a string describing a dict or a dict.
        if type(key) == str:
            temp_key.update(ast.literal_eval(key))
        else:
            temp_key.update(key)
        # This is a bit of a hack to get around python 2 treating unicode strings
        # differently.  Cerberus will throw a 400 if we try to post python 2 style
        # unicode stings as the payload.
        combined_key = json.encoder.JSONEncoder().encode(temp_key)
        return combined_key
1042088
def decrypt(data, opts={})
      data = data.to_s
      raise "No private key set!" unless @key.private?
      unless opts[:binary]
        data = Base64.decode64(data)
      end
      @key.private_decrypt(data)
    end
914713
def todict(self):
        
        return {"f_key": hb_encode(self.f_key),
                "alpha_key": hb_encode(self.alpha_key),
                "chunks": self.chunks,
                "encrypted": self.encrypted,
                "iv": hb_encode(self.iv),
                "hmac": hb_encode(self.hmac)}
1201048
def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
    ''

    encrypter = Encrypter(mode, padding = padding)
    _feed_stream(encrypter, in_stream, out_stream, block_size)
1194800
def encrypt(self, paddedPlaintext):
        
        # TODO: make this less ugly and python 2 and 3 compatible
        # paddedMessage = bytearray(paddedMessage.encode() if (sys.version_info >= (3, 0) and not type(paddedMessage) in (bytes, bytearray)) or type(paddedMessage) is unicode else paddedMessage)
        if (sys.version_info >= (3, 0) and
                not type(paddedPlaintext) in (bytes, bytearray)) or type(paddedPlaintext) is unicode:
            paddedPlaintext = bytearray(paddedPlaintext.encode())
        else:
            paddedPlaintext = bytearray(paddedPlaintext)
        try:
            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)
            senderKeyState = record.getSenderKeyState()
            senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey()
            ciphertext = self.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)

            senderKeyMessage = SenderKeyMessage(senderKeyState.getKeyId(),
                                                senderKey.getIteration(),
                                                ciphertext,
                                                senderKeyState.getSigningKeyPrivate())

            senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext())
            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)

            return senderKeyMessage.serialize()
        except InvalidKeyIdException as e:
            raise NoSessionException(e)
1227084
def _convert_key_to_str(key):
    '''
    
    '''
    # IMPORTANT: on PY2, the secret key must be str and not unicode to work
    # properly with hmac.new (see http://bugs.python.org/issue5285)
    #
    # pylint: disable=incompatible-py3-code,undefined-variable
    return salt.utils.data.encode(key) \
        if six.PY2 and isinstance(key, unicode) \
        else key