:param encrypted: True to enforce encryption (will raise exception unless key is set),
        False to prevent encryption or None to encrypt if key is set.
183134
def _uploadStream(self, jobStoreFileID, container, checkForModification=False, encrypted=None):
        
        if checkForModification:
            try:
                expectedVersion = container.get_blob_properties(blob_name=str(jobStoreFileID)).properties.etag
            except AzureMissingResourceHttpError:
                expectedVersion = None

        if encrypted is None:
            encrypted = self.keyPath is not None
        elif encrypted:
            if self.keyPath is None:
                raise RuntimeError('Encryption requested but no key was provided')

        maxBlockSize = self._maxAzureBlockBytes
        if encrypted:
            # There is a small overhead for encrypted data.
            maxBlockSize -= encryption.overhead

        store = self

        class UploadPipe(WritablePipe):

            def readFrom(self, readable):
                blocks = []
                try:
                    while True:
                        buf = readable.read(maxBlockSize)
                        if len(buf) == 0:
                            # We're safe to break here even if we never read anything, since
                            # putting an empty block list creates an empty blob.
                            break
                        if encrypted:
                            buf = encryption.encrypt(buf, store.keyPath)
                        blockID = store._newFileID()
                        container.put_block(blob_name=str(jobStoreFileID),
                                            block=buf,
                                            block_id=blockID)
                        blocks.append(BlobBlock(blockID))
                except:
                    with panic(log=logger):
                        # This is guaranteed to delete any uncommitted blocks.
                        container.delete_blob(blob_name=str(jobStoreFileID))

                if checkForModification and expectedVersion is not None:
                    # Acquire a (60-second) write lock,
                    leaseID = container.acquire_blob_lease(blob_name=str(jobStoreFileID),
                                                           lease_duration=60)
                    # check for modification,
                    blob = container.get_blob_properties(blob_name=str(jobStoreFileID))
                    if blob.properties.etag != expectedVersion:
                        container.release_blob_lease(blob_name=str(jobStoreFileID), lease_id=leaseID)
                        raise ConcurrentFileModificationException(jobStoreFileID)
                    # commit the file,
                    container.put_block_list(blob_name=str(jobStoreFileID),
                                             block_list=blocks,
                                             lease_id=leaseID,
                                             metadata=dict(encrypted=str(encrypted)))
                    # then release the lock.
                    container.release_blob_lease(blob_name=str(jobStoreFileID), lease_id=leaseID)
                else:
                    # No need to check for modification, just blindly write over whatever
                    # was there.
                    container.put_block_list(blob_name=str(jobStoreFileID),
                                             block_list=blocks,
                                             metadata=dict(encrypted=str(encrypted)))

        with UploadPipe() as writable:
            yield writable
1173867
def encrypt(self, password):
        
        if not password or not self._crypter:
            return password or b''
        return self._crypter.encrypt(password)
315767
def encrypt_password(**kwargs):
    
    new_value = kwargs['new_value']
    field = kwargs['field']
    min_length = field.params['min_length']
    if len(new_value) < min_length:
        raise ValueError(
            '`{}`: Value length must be more than {}'.format(
                field.name, field.params['min_length']))

    if new_value and not crypt.match(new_value):
        new_value = str(crypt.encode(new_value))
    return new_value
204174
def block_encrypt(plain_text, jwe = nil)
      jwe ||= block_encryptor
      return JOSE::JWE.block_encrypt(self, plain_text, jwe)
    end
866384
def update_and_reencrypt(self, **kwargs):
        
        encrypted_field_name = self.store.model_class.__plaintext__

        id_ = kwargs[self.identifier_key]
        current_model = self.store.retrieve(id_)
        current_value = current_model.plaintext

        null_update = (
            # Check if the update is for the encrypted field, and if it's explicitly set to null
            encrypted_field_name in kwargs
            and kwargs.get(encrypted_field_name) is None
        )
        new_value = kwargs.pop(self.store.model_class.__plaintext__, None)
        use_new_value = new_value is not None or null_update

        updated_value = new_value if use_new_value else current_value

        model_kwargs = {
            self.identifier_key: id_,
            encrypted_field_name: updated_value,
            **kwargs,
        }

        return super().update(
            **model_kwargs,
        )
393854
def encrypt_to(self, f, mac_bytes=10):
        
        ctx = EncryptionContext(f, self.p, mac_bytes)
        yield ctx
        ctx.finish()
373289
def encrypt_binary(self, binary, *args, **kwargs):
        
        return self.encrypt(binary, *args, **kwargs)
919319
def decrypt(self):
        
        if not self._crypter:
            return b''
        try:
            plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params)
            return plaintext
        except Exception as e:
            exc_info = sys.exc_info()
            six.reraise(
                ValueError('Invalid ciphertext "%s", error: %s' % (self._ciphertext, e)),
                None,
                exc_info[2]
            )
731329
def encrypted_to(self, raw_data):
        """"""
        # TODO: make this support multiple keys.
        result = self._gpg.list_packets(raw_data)
        if not result.key:
            raise LookupError(
                "Content is not encrypted to a GnuPG key!")
        try:
            return self.find_key_by_keyid(result.key)
        except:
            return self.find_key_by_subkey(result.key)
1309570
def decrypt(encoded, key: nil)

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

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

      cipher.update(encoded)+cipher.final

    end
1093789
def decrypt(cipher, plain = Data.new)
      err = GPGME::gpgme_op_decrypt(self, cipher, plain)
      exc = GPGME::error_to_exception(err)
      raise exc if exc
      plain
    end
39286
function encrypt (str) {
    var cipher = crypto.createCipher(algorithm, key)
      , crypted = cipher.update(str, from, to) + cipher.final(to)
    return crypted;
  }
111023
public function decrypt($encrypted, $key)
	{
		if (empty($encrypted))
			return null;

		list($identifier, $input) = explode(self::SEPARATOR_ALGORITHM, $encrypted, 2);

		if ($identifier !== self::IDENTIFIER)
			throw new Exception('Encryption can not be decrypted. Unsupported identifier: ' . $identifier);

		// Split the input into its parts
		$cipherSplit = explode(self::SEPARATOR_CRYPTO_PARTS, $input);
		$originalSize = intval($cipherSplit[0]);
		$iv = cryptoHelpers::toNumbers($cipherSplit[1]);
		$cipherText = $cipherSplit[2];

		// Set up encryption parameters
		$cipherIn = cryptoHelpers::toNumbers($cipherText);
		$keyAsNumbers = cryptoHelpers::toNumbers(bin2hex($key));
		$keyLength = count($keyAsNumbers);

		$decrypted = AES::decrypt(
			$cipherIn,
			$originalSize,
			AES::modeOfOperation_CBC,
			$keyAsNumbers,
			$keyLength,
			$iv
		);

		// Byte-array to text.
		$hexDecrypted = cryptoHelpers::toHex($decrypted);
		$retVal = pack("H*", $hexDecrypted);

		return $retVal;
	}
1312121
def encrypt_to_file(contents, filename):
    
    if not filename.endswith('.enc'):
        raise ValueError("%s does not end with .enc" % filename)

    key = Fernet.generate_key()
    fer = Fernet(key)

    encrypted_file = fer.encrypt(contents)

    with open(filename, 'wb') as f:
        f.write(encrypted_file)

    return key
4064
def encrypt(self, txt, key):
        
        # log.debug("encrypt(txt='%s', key='%s')", txt, key)
        assert isinstance(txt, six.text_type), "txt: %s is not text type!" % repr(txt)
        assert isinstance(key, six.text_type), "key: %s is not text type!" % repr(key)

        if len(txt) != len(key):
            raise SecureJSLoginError("encrypt error: %s and '%s' must have the same length!" % (txt, key))

        pbkdf2_hash = PBKDF2SHA1Hasher1().get_salt_hash(txt)

        txt=force_bytes(txt)
        key=force_bytes(key)
        crypted = self.xor(txt, key)
        crypted = binascii.hexlify(crypted)
        crypted = six.text_type(crypted, "ascii")
        return "%s$%s" % (pbkdf2_hash, crypted)
204092
def encrypt_password(self):
        
        if self.password and not self.password.startswith('$pbkdf2'):
            self.set_password(self.password)
637948
def Decrypt(self, encrypted_data):
    
    decrypted_data = self._rc4_cipher.decrypt(encrypted_data)
    return decrypted_data, b''