Get decryption key for a given S3 object

        :param key: Base64 decoded version of x-amz-key
        :param material_description: JSON decoded x-amz-matdesc
        :return: Raw AES key bytes
433195
async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
        

        # So it seems when java just calls Cipher.getInstance('AES') it'll default to AES/ECB/PKCS5Padding
        aesecb = self._cipher.decryptor()
        padded_result = await self._loop.run_in_executor(None, lambda: (aesecb.update(key) + aesecb.finalize()))

        unpadder = PKCS7(AES.block_size).unpadder()
        result = await self._loop.run_in_executor(None, lambda: (unpadder.update(padded_result) + unpadder.finalize()))

        return result
641679
def decrypt_aes_cbc(ciphertext, key, iv):
    
    if not isinstance(ciphertext, bytes):
        raise TypeError("content to decrypt must by bytes.")
    
    # Just decrypt the content with the created key
    aes = AES.new(key, AES.MODE_CBC, iv)
    decrypted_content = aes.decrypt(ciphertext)
    padding = ord(decrypted_content[-1:len(decrypted_content)])  # This is a difference in python2 vs python3, so we are explicit about
                                            # the range so that return value is the same.
    decrypted_content = decrypted_content[:len(decrypted_content) - padding]
    return decrypted_content
990632
def get_key(self, path):
        
        (bucket, key) = self._path_to_bucket_and_key(path)

        if self._exists(bucket, key):
            return self.s3.ObjectSummary(bucket, key)
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
655676
def _key(self):
        
        return Key(self._schema.key_type, self._identity, self._name,
                   [str(item.value) for item in self._dimension_fields.values()])
488515
def get_as_bytes(self, s3_path):
        
        (bucket, key) = self._path_to_bucket_and_key(s3_path)
        obj = self.s3.Object(bucket, key)
        contents = obj.get()['Body'].read()
        return contents
641405
def get_key_for_enctype(self, etype):
		
		if etype == EncryptionType.AES256_CTS_HMAC_SHA1_96:
			if self.kerberos_key_aes_256:
				return bytes.fromhex(self.kerberos_key_aes_256)
			if self.password is not None:
				salt = (self.domain.upper() + self.username).encode()
				return string_to_key(Enctype.AES256, self.password.encode(), salt).contents
			raise Exception('There is no key for AES256 encryption')
		elif etype == EncryptionType.AES128_CTS_HMAC_SHA1_96:
			if self.kerberos_key_aes_128:
				return bytes.fromhex(self.kerberos_key_aes_128)
			if self.password is not None:
				salt = (self.domain.upper() + self.username).encode()
				return string_to_key(Enctype.AES128, self.password.encode(), salt).contents
			raise Exception('There is no key for AES128 encryption')
		elif etype == EncryptionType.ARCFOUR_HMAC_MD5:
			if self.kerberos_key_rc4:
				return bytes.fromhex(self.kerberos_key_rc4)
			if self.nt_hash:
				return bytes.fromhex(self.nt_hash)
			elif self.password:
				self.nt_hash = hashlib.new('md4', self.password.encode('utf-16-le')).hexdigest().upper()
				return bytes.fromhex(self.nt_hash)
			else:
				raise Exception('There is no key for RC4 encryption')
		elif etype == EncryptionType.DES3_CBC_SHA1:
			if self.kerberos_key_des3:
				return bytes.fromhex(self.kerberos_key_des)
			elif self.password:
				salt = (self.domain.upper() + self.username).encode()
				return string_to_key(Enctype.DES3, self.password.encode(), salt).contents
			else:
				raise Exception('There is no key for DES3 encryption')
				
		elif etype == EncryptionType.DES_CBC_MD5: #etype == EncryptionType.DES_CBC_CRC or etype == EncryptionType.DES_CBC_MD4 or 
			if self.kerberos_key_des:
				return bytes.fromhex(self.kerberos_key_des)
			elif self.password:
				salt = (self.domain.upper() + self.username).encode()
				return string_to_key(Enctype.DES_MD5, self.password.encode(), salt).contents
			else:
				raise Exception('There is no key for DES3 encryption')
		
		else:
			raise Exception('Unsupported encryption type: %s' % etype.name)
32425
def decrypt(self, encrypted):
        
        fernet = Fernet(self.decryption_cipher_key)
        return fernet.decrypt(encrypted)
327726
def key_hash(key):
    
    hashed = hashlib.md5()
    for k, v in sorted(key.items()):
        hashed.update(str(v).encode())
    return hashed.hexdigest()
186775
private S3Object decipherWithInstFileSuffix(GetObjectRequest req,
            long[] desiredRange, long[] cryptoRange, S3Object retrieved,
            String instFileSuffix) {
        final S3ObjectId id = req.getS3ObjectId();
        // Check if encrypted info is in an instruction file
        final S3ObjectWrapper ifile = fetchInstructionFile(id, instFileSuffix);
        if (ifile == null) {
            throw new SdkClientException("Instruction file with suffix "
                    + instFileSuffix + " is not found for " + retrieved);
        }
        try {
            return decipherWithInstructionFile(req, desiredRange,
                    cryptoRange, new S3ObjectWrapper(retrieved, id), ifile);
        } finally {
            closeQuietly(ifile, log);
        }
    }
880109
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
        

        random_bytes = os.urandom(32)

        padder = PKCS7(AES.block_size).padder()
        padded_result = await self._loop.run_in_executor(
            None, lambda: (padder.update(random_bytes) + padder.finalize()))

        aesecb = self._cipher.encryptor()
        encrypted_result = await self._loop.run_in_executor(
            None, lambda: (aesecb.update(padded_result) + aesecb.finalize()))

        return random_bytes, {}, base64.b64encode(encrypted_result).decode()
1128274
def decrypt(self, recipient_key):
        
        if recipient_key.private_key is None:
            raise ValueError("Cannot decrypt with this key; no private key part found.")
        header = MiniLockHeader(self.header)
        # Create ephemeral public key for authenticated decryption of metadata.
        # TODO: Future-proof this by making it try to decrypt a b58 ephem ID if available?
        decryptInfo = header.decrypt(recipient_key)
        file_info = decryptInfo['fileInfo']
        file_hash = file_info['fileHash']
        if not b64decode(file_hash) == pyblake2.blake2s(self.chunks_block).digest():
            raise ValueError("ciphertext does not match given hash!")
        symbox = SymmetricMiniLock.from_key(b64decode(file_info['fileKey']))
        filename, *filechunks = symbox.decrypt(self.chunks_block, b64decode(file_info['fileNonce']))
        try:
            filename = filename.decode('utf8')
        except Exception as E:
            raise ValueError("Cannot decode filename to UTF8 string: '{}'".format(filename))
        sender = decryptInfo['senderID']
        return filename, sender, b''.join(filechunks)
910662
def serialize_encryption_context(encryption_context):
    
    if not encryption_context:
        return bytes()

    serialized_context = bytearray()
    dict_size = len(encryption_context)

    if dict_size > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
        raise SerializationError("The encryption context contains too many elements.")

    serialized_context.extend(struct.pack(">H", dict_size))

    # Encode strings first to catch bad values.
    encryption_context_list = []
    for key, value in encryption_context.items():
        try:
            if isinstance(key, bytes):
                key = codecs.decode(key)
            if isinstance(value, bytes):
                value = codecs.decode(value)
            encryption_context_list.append(
                (aws_encryption_sdk.internal.str_ops.to_bytes(key), aws_encryption_sdk.internal.str_ops.to_bytes(value))
            )
        except Exception:
            raise SerializationError(
                "Cannot encode dictionary key or value using {}.".format(aws_encryption_sdk.internal.defaults.ENCODING)
            )

    for key, value in sorted(encryption_context_list, key=lambda x: x[0]):
        serialized_context.extend(
            struct.pack(
                ">H{key_size}sH{value_size}s".format(key_size=len(key), value_size=len(value)),
                len(key),
                key,
                len(value),
                value,
            )
        )
        if len(serialized_context) > aws_encryption_sdk.internal.defaults.MAX_BYTE_ARRAY_SIZE:
            raise SerializationError("The serialized context is too large.")
    return bytes(serialized_context)
1351349
def _key_digest(self, secret_key):
        
        '''
            
        '''
        
        from hashlib import md5, sha256
        from base64 import b64encode
        key_bytes = sha256(secret_key.encode('utf-8')).digest()
        key_b64 = b64encode(key_bytes).decode()
        digest_bytes = md5(key_bytes).digest()
        digest_b64 = b64encode(digest_bytes).decode()
        
        return key_b64, digest_b64
1361865
def _key(self):
        
        return (
            self._name,
            self._field_type.upper(),
            self._mode.upper(),
            self._description,
            self._fields,
        )
354084
def _encode_key(self, obj):
        """"""

        if obj.__class__ is str:
            return self._encode_str(obj)

        if obj.__class__ is UUID:
            return '"' + str(obj) + '"'

        # __mm_serialize__ is called before any isinstance checks (but after exact type checks)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode_key(data)

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        # if everything else failed try the default() method and re-raise any TypeError
        # exceptions as more specific "not a valid dict key" TypeErrors
        try:
            value = self.default(obj)
        except TypeError:
            raise TypeError('{!r} is not a valid dictionary key'.format(obj))

        return self._encode_key(value)
166514
def get_key(self, key_id):
        
        url = ENCRYPTION_KEY_URL.format(key_id)
        return self._key_from_json(self._get_resource(url))