def test_decrypt_failure_discovery_disallowed_partition(self):
        """Test that a KMS Master Key Provider in filtered discovery mode fails to
        decrypt an EDK if the EDK was wrapped by a KMS Master Key in an
        AWS partition that is not allowed by the filter.
        """
        cmk_arn = get_cmk_arn()
        encrypt_provider = StrictAwsKmsMasterKeyProvider(key_ids=[cmk_arn])

        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            key_provider=encrypt_provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        # Check that we can decrypt the ciphertext using the original provider
        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=encrypt_provider
        )
        assert plaintext == VALUES["plaintext_128"]

        # Check that we cannot decrypt the ciphertext using a discovery provider that does not match this key's
        # partition
        arn = arn_from_str(cmk_arn)
        discovery_filter = DiscoveryFilter(partition="aws-cn", account_ids=[arn.account_id])
        decrypt_provider = DiscoveryAwsKmsMasterKeyProvider(discovery_filter=discovery_filter)

        with pytest.raises(MasterKeyProviderError) as excinfo:
            aws_encryption_sdk.EncryptionSDKClient().decrypt(source=ciphertext, key_provider=decrypt_provider)
        excinfo.match("not allowed by this Master Key Provider")
    def test_decrypt_success_discovery_no_filter(self):
        """Test that a Discovery KMS Master Key Provider in unfiltered discovery mode can
        decrypt a valid EDK.
        """
        cmk_arn = get_cmk_arn()
        encrypt_provider = StrictAwsKmsMasterKeyProvider(key_ids=[cmk_arn])

        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            key_provider=encrypt_provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        # Check that we can decrypt the ciphertext using the original provider
        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=encrypt_provider
        )
        assert plaintext == VALUES["plaintext_128"]

        # Check that we can decrypt the ciphertext using a discovery provider with no filter
        decrypt_provider = DiscoveryAwsKmsMasterKeyProvider()

        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=decrypt_provider
        )
        assert plaintext == VALUES["plaintext_128"]
    def test_decrypt_failure_strict_mismatched_key_id(self):
        """Test that a Strict KMS Master Key Provider fails to decrypt an
        EDK when it has not been configured with the correct key id
        """
        cmk_arn = get_cmk_arn()
        encrypt_provider = StrictAwsKmsMasterKeyProvider(key_ids=[cmk_arn])

        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            key_provider=encrypt_provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        # Check that we can decrypt the ciphertext using the original provider
        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=encrypt_provider
        )
        assert plaintext == VALUES["plaintext_128"]

        # Check that we cannot decrypt the ciphertext using a non-discovery provider without the correct key_id
        second_cmk_arn = cmk_arn + "-doesnotexist"
        decrypt_provider = StrictAwsKmsMasterKeyProvider(key_ids=[second_cmk_arn])

        with pytest.raises(DecryptKeyError) as excinfo:
            aws_encryption_sdk.EncryptionSDKClient().decrypt(source=ciphertext, key_provider=decrypt_provider)
        excinfo.match("Unable to decrypt any data key")
    def test_decrypt_success_discovery_filter(self):
        """Test that a Discovery KMS Master Key Provider in filtered discovery mode can
        decrypt a ciphertext when it is configured with the correct account id and partition.
        """
        cmk_arn = get_cmk_arn()
        encrypt_provider = StrictAwsKmsMasterKeyProvider(key_ids=[cmk_arn])

        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            key_provider=encrypt_provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        # Check that we can decrypt the ciphertext using the original provider
        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=encrypt_provider
        )
        assert plaintext == VALUES["plaintext_128"]

        # Check that we can decrypt the ciphertext using a discovery provider that allows this account and partition
        arn = arn_from_str(cmk_arn)
        discovery_filter = DiscoveryFilter(partition=arn.partition, account_ids=[arn.account_id])
        decrypt_provider = DiscoveryAwsKmsMasterKeyProvider(discovery_filter=discovery_filter)

        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=decrypt_provider
        )
        assert plaintext == VALUES["plaintext_128"]
def test_decryptor_deprecated_attributes(caplog, attribute, no_later_than):
    caplog.set_level(logging.WARNING)
    plaintext = exact_length_plaintext(100)
    key_provider = fake_kms_key_provider()
    ciphertext, _header = aws_encryption_sdk.EncryptionSDKClient().encrypt(
        source=plaintext, key_provider=key_provider, frame_length=0)
    with aws_encryption_sdk.EncryptionSDKClient().stream(
            mode="decrypt", source=ciphertext,
            key_provider=key_provider) as decryptor:
        decrypted = decryptor.read()

    assert decrypted == plaintext
    if aws_encryption_sdk.__version__ < no_later_than:
        _assert_deprecated_but_not_yet_removed(
            logcap=caplog,
            instance=decryptor,
            attribute_name=attribute,
            error_message=
            "StreamDecryptor.{name} is deprecated and will be removed in {version}"
            .format(name=attribute, version=no_later_than),
            no_later_than=no_later_than,
        )
    else:
        _assert_decrypted_and_removed(instance=decryptor,
                                      attribute_name=attribute,
                                      removed_in=no_later_than)
 def test_encryption_cycle_default_algorithm_non_framed_no_encryption_context(self):
     """Test that the enrypt/decrypt cycle completes successfully
     for a non-framed message using the default algorithm.
     """
     ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
         source=VALUES["plaintext_128"], key_provider=self.kms_master_key_provider, frame_length=0
     )
     plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
         source=ciphertext, key_provider=self.kms_master_key_provider
     )
     assert plaintext == VALUES["plaintext_128"]
def test_decrypt_oneshot_no_seek_input():
    """Test that decrypt can handle an input stream that is not seekable."""
    key_provider = fake_kms_key_provider()
    ciphertext, _header = aws_encryption_sdk.EncryptionSDKClient().encrypt(
        source=VALUES["plaintext_128"],
        key_provider=key_provider,
        encryption_context=VALUES["encryption_context"])
    ciphertext_no_seek = NoSeekBytesIO(ciphertext)
    decrypted, _header = aws_encryption_sdk.EncryptionSDKClient().decrypt(
        source=ciphertext_no_seek, key_provider=key_provider)
    assert decrypted == VALUES["plaintext_128"]
def test_decrypt_minimal_source_stream_api(frame_length, wrapping_class):
    plaintext = exact_length_plaintext(100)
    key_provider = fake_kms_key_provider()
    raw_ciphertext, _encrypt_header = aws_encryption_sdk.EncryptionSDKClient(
    ).encrypt(source=plaintext,
              key_provider=key_provider,
              frame_length=frame_length)
    ciphertext = wrapping_class(io.BytesIO(raw_ciphertext))
    decrypted, _decrypt_header = aws_encryption_sdk.EncryptionSDKClient(
    ).decrypt(source=ciphertext, key_provider=key_provider)
    assert plaintext == decrypted
Example #9
0
    def test_decrypt_unsigned_failure_signed_message(self):
        """Test that "decrypt-unsigned" mode rejects signed messages."""
        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            key_provider=self.kms_master_key_provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        with aws_encryption_sdk.EncryptionSDKClient().stream(
            source=io.BytesIO(ciphertext), key_provider=self.kms_master_key_provider, mode="decrypt-unsigned"
        ) as decryptor:
            with pytest.raises(ActionNotAllowedError) as excinfo:
                decryptor.read()
            excinfo.match("Configuration conflict. Cannot decrypt signed message in decrypt-unsigned mode.")
 def test_encryption_cycle_default_algorithm_multiple_frames(self):
     """Test that the enrypt/decrypt cycle completes successfully
     for a framed message with multiple frames using the
     default algorithm.
     """
     ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
         source=VALUES["plaintext_128"] * 100,
         key_provider=self.kms_master_key_provider,
         encryption_context=VALUES["encryption_context"],
         frame_length=1024,
     )
     plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
         source=ciphertext, key_provider=self.kms_master_key_provider
     )
     assert plaintext == VALUES["plaintext_128"] * 100
Example #11
0
    def test_decrypt_unsigned_success_unsigned_message(self):
        """Test that "decrypt-unsigned" mode accepts unsigned messages."""
        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            algorithm=Algorithm.AES_256_GCM_HKDF_SHA512_COMMIT_KEY,
            key_provider=self.kms_master_key_provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        with aws_encryption_sdk.EncryptionSDKClient().stream(
            source=io.BytesIO(ciphertext), key_provider=self.kms_master_key_provider, mode="decrypt-unsigned"
        ) as decryptor:
            plaintext = decryptor.read()
            assert plaintext == VALUES["plaintext_128"]
Example #12
0
def encryptionSDKDemo():
    import aws_encryption_sdk
    from aws_encryption_sdk.identifiers import CommitmentPolicy

    #
    # Create AWS encryption sdk client with
    #
    client = aws_encryption_sdk.EncryptionSDKClient(
        commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)

    kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(
        key_ids=[MASTER_KEY_ARN])

    #
    # My secret string
    #
    my_plaintext = b'This is some super secret data!'
    print(' Plain text to encrypt = %s \n ' % my_plaintext)

    #
    # Let's encrypt the plaintext data
    #
    print(" let's encrypt ! \n")
    my_ciphertext, encryptor_header = client.encrypt(
        source=my_plaintext, key_provider=kms_key_provider)
    print(' My ciphered text  = %s \n ' % my_ciphertext)

    #
    # Let's decrypt the ciphertext data
    #
    print(" let's decrypt ! \n")
    decrypted_plaintext, decryptor_header = client.decrypt(
        source=my_ciphertext, key_provider=kms_key_provider)
    print(' My ciphered text  decrypt = %s \n ' % decrypted_plaintext)
def test_encryption_cycle_stream_kms(frame_length, algorithm,
                                     encryption_context):
    commitment_policy = CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
    if not algorithm.is_committing():
        commitment_policy = CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT
    key_provider = fake_kms_key_provider(algorithm.kdf_input_len)
    client = aws_encryption_sdk.EncryptionSDKClient(
        commitment_policy=commitment_policy)

    ciphertext = bytearray()
    with client.stream(
            mode="e",
            source=VALUES["plaintext_128"] * 10,
            key_provider=key_provider,
            frame_length=frame_length,
            algorithm=algorithm,
            encryption_context=encryption_context,
    ) as encryptor:
        for chunk in encryptor:
            ciphertext.extend(chunk)
    ciphertext = bytes(ciphertext)

    plaintext = bytearray()
    with client.stream(mode="d",
                       source=io.BytesIO(ciphertext),
                       key_provider=key_provider) as decryptor:
        for chunk in decryptor:
            plaintext.extend(chunk)
    plaintext = bytes(plaintext)

    assert ciphertext != plaintext
    assert plaintext == VALUES["plaintext_128"] * 10
    assert encryptor.header.encryption_context == decryptor.header.encryption_context
def test_encryption_cycle_raw_mkp_openssl_102_plus(wrapping_algorithm,
                                                   encryption_key_type):
    decryption_key_type = EncryptionKeyType.PRIVATE
    encrypting_key_provider = build_fake_raw_key_provider(
        wrapping_algorithm, encryption_key_type)
    decrypting_key_provider = build_fake_raw_key_provider(
        wrapping_algorithm, decryption_key_type)
    ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
        source=VALUES["plaintext_128"],
        key_provider=encrypting_key_provider,
        encryption_context=VALUES["encryption_context"],
        frame_length=0,
    )
    plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
        source=ciphertext, key_provider=decrypting_key_provider)
    assert plaintext == VALUES["plaintext_128"]
Example #15
0
    def __encrypt_decrypt_file(self, mode: str) -> None:
        try:
            client = aws_encryption_sdk.EncryptionSDKClient(
                commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
            )
            print(f"client = {client}")
            master_key_provider = get_master_key_provider(self.key)
            with open(self.input_file_path, "rb") as input_text, open(
                self.output_file_path, "wb"
            ) as output_text:
                print(f"client.stream={client.stream}")
                with client.stream(
                    mode=mode, source=input_text, key_provider=master_key_provider
                ) as encryptor_decryptor:
                    print(f"encryptor_decryptor={encryptor_decryptor}")
                    for index, chunk in enumerate(encryptor_decryptor):
                        output_text.write(chunk)
                        logger.debug(f"Wrote chunk {index}")

        except Exception as e:
            logger.error(e)
            logger.error(
                f"Args: input_file_path={self.input_file_path}, "
                + f"output_file_path={self.output_file_path}"
            )
            raise EncryptionError(" s3encrypt.encryption encountered an error ", e)
def test_no_infinite_encryption_cycle_on_empty_source():
    """This catches a race condition where when calling encrypt with
    an empty byte string, encrypt would enter an infinite loop.
    If this test does not hang, the race condition is not present.
    """
    aws_encryption_sdk.EncryptionSDKClient().encrypt(
        source=b"", key_provider=fake_kms_key_provider())
Example #17
0
    def run(self, ciphertext_writer, plaintext_uri):
        """Run this scenario, writing the resulting ciphertext with ``ciphertext_writer`` and returning
        a :class:`MessageDecryptionTestScenario` that describes the matching decrypt scenario.

        :param callable ciphertext_writer: Callable that will write the requested named ciphertext and
            return a URI locating the written data
        :param str plaintext_uri: URI locating the written plaintext data for this scenario
        :return: Decrypt test scenario that describes the generated scenario
        :rtype: MessageDecryptionTestScenario
        """
        client = aws_encryption_sdk.EncryptionSDKClient(
            commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)
        ciphertext, _header = client.encrypt(
            source=self.plaintext,
            algorithm=self.algorithm,
            frame_length=self.frame_size,
            encryption_context=self.encryption_context,
            key_provider=self.master_key_provider,
        )

        ciphertext_name = str(uuid.uuid4())
        ciphertext_uri = ciphertext_writer(ciphertext_name, ciphertext)

        return MessageDecryptionTestScenario(
            plaintext_uri=plaintext_uri,
            plaintext=self.plaintext,
            ciphertext_uri=ciphertext_uri,
            ciphertext=ciphertext,
            master_key_specs=self.master_key_specs,
            master_key_provider=self.master_key_provider,
        )
def encrypt_decrypt(key_arn, source_plaintext, botocore_session=None):
    """Encrypts and then decrypts a string under one KMS customer master key (CMK).

    :param str key_arn: Amazon Resource Name (ARN) of the KMS CMK
    :param bytes source_plaintext: Data to encrypt
    :param botocore_session: existing botocore session instance
    :type botocore_session: botocore.session.Session
    """
    kwargs = dict(key_ids=[key_arn])

    if botocore_session is not None:
        kwargs["botocore_session"] = botocore_session

    # Set up an encryption client with an explicit commitment policy disallowing encryption with algorithms that
    # provide commitment
    client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)

    # Create master key provider using the ARN of the key and the session (botocore_session)
    kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(**kwargs)

    # Encrypt the plaintext using the AWS Encryption SDK. It returns the encrypted message and the header. Note: in
    # order for decrypt to succeed, the key_ids value must be the key ARN of the CMK.
    ciphertext, encrypted_message_header = client.encrypt(source=source_plaintext, key_provider=kms_key_provider)

    # Decrypt the encrypted message using the AWS Encryption SDK. It returns the decrypted message and the header
    plaintext, decrypted_message_header = client.decrypt(source=ciphertext, key_provider=kms_key_provider)

    # Verify that the original message and the decrypted message are the same
    assert source_plaintext == plaintext

    # Verify that the encryption context of the encrypted message and decrypted message match
    assert all(
        pair in encrypted_message_header.encryption_context.items()
        for pair in decrypted_message_header.encryption_context.items()
    )
Example #19
0
def test_threading_loop_with_common_cache():
    """Test thread safety of client while using common cryptographic materials cache across all threads."""
    # Check for the CMK ARN first to fail fast if it is not available
    get_cmk_arn()
    rounds = 20
    cache = aws_encryption_sdk.LocalCryptoMaterialsCache(capacity=40)
    client = aws_encryption_sdk.EncryptionSDKClient()
    plaintext_inputs = [
        dict(input_value=copy.copy(PLAINTEXT),
             start_pause=random_pause_time(),
             cache=cache) for _round in range(rounds)
    ]

    ciphertext_values = get_all_thread_outputs(crypto_function=client.encrypt,
                                               thread_inputs=plaintext_inputs)
    ciphertext_inputs = [
        dict(input_value=ciphertext,
             start_pause=random_pause_time(),
             cache=cache) for ciphertext in ciphertext_values
    ]

    decrypted_values = get_all_thread_outputs(crypto_function=client.decrypt,
                                              thread_inputs=ciphertext_inputs)

    assert all(value == PLAINTEXT for value in decrypted_values)
def test_encrypt_load_header_v2():
    """Test that StreamEncryptor can extract header without reading plaintext."""
    # Using a non-signed algorithm to simplify header size calculation
    algorithm = aws_encryption_sdk.Algorithm.AES_256_GCM_HKDF_SHA512_COMMIT_KEY
    key_provider = fake_kms_key_provider(algorithm.kdf_input_len)

    header_length = 1  # version
    header_length += 2  # algorithm id
    header_length += 32  # message id
    header_length += 2  # aad len
    s = serialize_encryption_context(VALUES["encryption_context"])
    header_length += len(s)
    header_length += 2  # encrypted data key count
    header_length += 6 + 7 + len(VALUES["arn"]) + len(
        VALUES["data_keys"][algorithm.kdf_input_len]["encrypted"])
    header_length += 1  # content type
    header_length += 4  # frame length
    header_length += 32  # algorithm suite data
    header_length += algorithm.auth_len  # authentication tag

    with aws_encryption_sdk.EncryptionSDKClient().stream(
            mode="e",
            source=VALUES["plaintext_128"],
            key_provider=key_provider,
            encryption_context=VALUES["encryption_context"],
            algorithm=algorithm,
            frame_length=1024,
    ) as encryptor:
        encryptor_header = encryptor.header
    # Ensure that only the header has been written into the output buffer
    assert len(encryptor.output_buffer) == header_length
    assert encryptor_header.encryption_context == VALUES["encryption_context"]
def test_init_success():
    test = aws_encryption_sdk.EncryptionSDKClient(
        commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT,
        max_encrypted_data_keys=1,
    )
    assert test.config.commitment_policy == CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT
    assert test.config.max_encrypted_data_keys == 1
def test_encrypt_decrypt_header_only():
    """Test that StreamDecryptor can extract header without reading ciphertext."""
    mkp = fake_kms_key_provider()
    ciphertext, encryptor_header = aws_encryption_sdk.EncryptionSDKClient(
    ).encrypt(
        source=VALUES["plaintext_128"],
        key_provider=mkp,
        encryption_context=VALUES["encryption_context"],
    )

    with aws_encryption_sdk.EncryptionSDKClient().stream(
            mode="d", source=ciphertext, key_provider=mkp) as decryptor:
        decryptor_header = decryptor.header
    assert decryptor.output_buffer == b""
    assert all(pair in decryptor_header.encryption_context.items()
               for pair in encryptor_header.encryption_context.items())
def basic_decrypt() -> Response:
    """Basic decrypt handler for decrypt oracle v0.

    **Request**

    * **Method**: POST
    * **Body**: Raw ciphertext bytes
    * **Headers**:

      * **Content-Type**: ``application/octet-stream``
      * **Accept**: ``application/octet-stream``

    **Response**

    * 200 response code with the raw plaintext bytes as the body
    * 400 response code with whatever error code was encountered as the body
    """
    APP.log.debug("Request:")
    APP.log.debug(json.dumps(APP.current_request.to_dict()))
    APP.log.debug("Ciphertext:")
    APP.log.debug(APP.current_request.raw_body)

    try:
        client = aws_encryption_sdk.EncryptionSDKClient()
        ciphertext = APP.current_request.raw_body
        plaintext, _header = client.decrypt(source=ciphertext, key_provider=_master_key_provider())
        APP.log.debug("Plaintext:")
        APP.log.debug(plaintext)
        response = Response(body=plaintext, headers={"Content-Type": "application/octet-stream"}, status_code=200)
    except Exception as error:  # pylint: disable=broad-except
        response = Response(body=str(error), status_code=400)

    APP.log.debug("Response:")
    APP.log.debug(json.dumps(response.to_dict(binary_types=["application/octet-stream"])))
    return response
Example #24
0
    def run(self, materials_manager=None):
        """Run this scenario, writing the resulting ciphertext with ``ciphertext_writer`` and returning
        a :class:`MessageDecryptionTestScenario` that describes the matching decrypt scenario.

        :param callable ciphertext_writer: Callable that will write the requested named ciphertext and
            return a URI locating the written data
        :param str plaintext_uri: URI locating the written plaintext data for this scenario
        :return: Decrypt test scenario that describes the generated scenario
        :rtype: MessageDecryptionTestScenario
        """
        commitment_policy = CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT
        if self.algorithm.is_committing():
            commitment_policy = CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT

        client = aws_encryption_sdk.EncryptionSDKClient(
            commitment_policy=commitment_policy)
        encrypt_kwargs = dict(
            source=self.plaintext,
            algorithm=self.algorithm,
            frame_length=self.frame_size,
            encryption_context=self.encryption_context,
        )
        if materials_manager:
            encrypt_kwargs["materials_manager"] = materials_manager
        else:
            encrypt_kwargs["key_provider"] = self.master_key_provider_fn()
        ciphertext, _header = client.encrypt(**encrypt_kwargs)
        return ciphertext
Example #25
0
 def __init__(  # noqa pylint: disable=too-many-arguments
         self,
         metadata_writer,  # type: MetadataWriter
         interactive,  # type: bool
         no_overwrite,  # type: bool
         decode_input,  # type: bool
         encode_output,  # type: bool
         required_encryption_context,  # type: Dict[str, str]
         required_encryption_context_keys,  # type: List[str]
         commitment_policy,  # type: CommitmentPolicy
         buffer_output,
         max_encrypted_data_keys,  # type: Union[None, int]
 ):
     # type: (...) -> None
     """Workaround pending resolution of attrs/mypy interaction.
     https://github.com/python/mypy/issues/2088
     https://github.com/python-attrs/attrs/issues/215
     """
     self.metadata_writer = metadata_writer
     self.interactive = interactive
     self.no_overwrite = no_overwrite
     self.decode_input = decode_input
     self.encode_output = encode_output
     self.required_encryption_context = required_encryption_context
     self.required_encryption_context_keys = required_encryption_context_keys  # pylint: disable=invalid-name
     self.buffer_output = buffer_output
     self.client = aws_encryption_sdk.EncryptionSDKClient(
         commitment_policy=commitment_policy,
         max_encrypted_data_keys=max_encrypted_data_keys,
     )
     attr.validate(self)
Example #26
0
def encrypt_value(data, prefix, key_provider):
    client = aws_encryption_sdk.EncryptionSDKClient(
        commitment_policy=aws_encryption_sdk.CommitmentPolicy.
        FORBID_ENCRYPT_ALLOW_DECRYPT, )
    ciphertext, encryptor_header = client.encrypt(source=data,
                                                  key_provider=key_provider)
    return prefix + base64.b64encode(ciphertext).decode('utf-8')
    def test_decrypt_success_strict_matching_key_id(self):
        """Test that a Strict KMS Master Key Provider can successfully
        decrypt an EDK when it has been configured with the correct key id
        """
        cmk_arn = get_cmk_arn()
        provider = StrictAwsKmsMasterKeyProvider(key_ids=[cmk_arn])
        ciphertext, _ = aws_encryption_sdk.EncryptionSDKClient().encrypt(
            source=VALUES["plaintext_128"],
            key_provider=provider,
            encryption_context=VALUES["encryption_context"],
            frame_length=1024,
        )

        plaintext, _ = aws_encryption_sdk.EncryptionSDKClient().decrypt(
            source=ciphertext, key_provider=self.kms_master_key_provider
        )
        assert plaintext == VALUES["plaintext_128"]
def test_plaintext_logs_oneshot(caplog, capsys, plaintext_length, frame_size):
    plaintext, key_provider = _prep_plaintext_and_logs(caplog,
                                                       plaintext_length)

    _ciphertext, _header = aws_encryption_sdk.EncryptionSDKClient().encrypt(
        source=plaintext, key_provider=key_provider, frame_length=frame_size)

    _look_in_logs(caplog, plaintext)
    _error_check(capsys)
Example #29
0
 def __init__(
     self,
     key_store: KeyStore,
     commitment_policy: CommitmentPolicy = CommitmentPolicy.
     REQUIRE_ENCRYPT_REQUIRE_DECRYPT,
 ) -> None:
     self._key_store = key_store
     self._client = aws_encryption_sdk.EncryptionSDKClient(
         commitment_policy=commitment_policy, )
    def run(self, name):
        """Run this test scenario

        :param str name: Descriptive name for this scenario to use in any logging or errors
        """
        client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT)
        plaintext, _header = client.decrypt(source=self.ciphertext, key_provider=self.master_key_provider)
        if plaintext != self.plaintext:
            raise ValueError("Decrypted plaintext does not match expected value for scenario '{}'".format(name))