

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Kit SDK de chiffrement AWS pour Python
<a name="python"></a>

Cette rubrique explique comment installer et utiliser le kit Kit SDK de chiffrement AWS pour Python. Pour plus de détails sur la programmation avec le Kit SDK de chiffrement AWS pour Python, consultez le [aws-encryption-sdk-python](https://github.com/aws/aws-encryption-sdk-python/)référentiel sur GitHub. Pour la documentation de l'API, veuillez consulter [Lire les documents](https://aws-encryption-sdk-python.readthedocs.io/en/latest/).

**Topics**
+ [Conditions préalables](#python-prerequisites)
+ [Installation](#python-installation)
+ [Exemples](python-example-code.md)

## Conditions préalables
<a name="python-prerequisites"></a>

Avant d'installer le Kit SDK de chiffrement AWS pour Python, assurez-vous de remplir les conditions préalables suivantes.

**Version prise en charge de Python**  
Python 3.8 ou version ultérieure est requis par les Kit SDK de chiffrement AWS pour Python versions 3.2.0 et ultérieures.  
La bibliothèque MPL ([AWS Cryptographic Material Providers Library](https://github.com/aws/aws-cryptographic-material-providers-library)) est une dépendance facultative de celle Kit SDK de chiffrement AWS pour Python introduite dans la version 4. *x.* Si vous avez l'intention d'installer le MPL, vous devez utiliser Python 3.11 ou version ultérieure.
Les versions antérieures du logiciel AWS Encryption SDK prennent en charge Python 2.7, Python 3.4 et versions ultérieures, mais nous vous recommandons d'utiliser la dernière version du AWS Encryption SDK.   
Pour télécharger Python, consultez [Téléchargements Python](https://www.python.org/downloads/).

**Outil d'installation pip pour Python**  
`pip`est inclus dans Python 3.6 et versions ultérieures, mais vous souhaiterez peut-être le mettre à niveau. Pour plus d'informations sur la mise à niveau ou l'installation`pip`, consultez la section [Installation](https://pip.pypa.io/en/latest/installation/) dans la `pip` documentation.

## Installation
<a name="python-installation"></a>

Installez la dernière version de Kit SDK de chiffrement AWS pour Python.

**Note**  
Toutes les versions Kit SDK de chiffrement AWS pour Python antérieures à 3.0.0 sont en [end-of-supportphase](https://docs.aws.amazon.com/sdkref/latest/guide/maint-policy.html#version-life-cycle).  
Vous pouvez effectuer la mise à jour en toute sécurité à partir de la version 2.0. *x* et versions ultérieures vers la dernière version du AWS Encryption SDK sans aucune modification du code ou des données. Cependant, de [nouvelles fonctionnalités de sécurité](about-versions.md#version-2) ont été introduites dans la version 2.0. *x* ne sont pas rétrocompatibles. Pour effectuer une mise à jour à partir de versions antérieures à 1.7. *x* vers la version 2.0. *x* et versions ultérieures, vous devez d'abord effectuer la mise à jour vers la dernière version 1. version *x* du AWS Encryption SDK. Pour en savoir plus, consultez [Migration de votre AWS Encryption SDK](migration.md).

`pip`À utiliser pour installer le Kit SDK de chiffrement AWS pour Python, comme indiqué dans les exemples suivants.

**Pour installer la dernière version**  

```
pip install "aws-encryption-sdk[MPL]"
```
Le `[MPL]` suffixe installe la bibliothèque MPL ([AWS Cryptographic Material Providers Library](https://github.com/aws/aws-cryptographic-material-providers-library)). Le MPL contient des structures permettant de chiffrer et de déchiffrer vos données. Le MPL est une dépendance optionnelle pour la version Kit SDK de chiffrement AWS pour Python introduite dans la version 4. *x.* Nous vous recommandons vivement d'installer le MPL. Toutefois, si vous n'avez pas l'intention d'utiliser le MPL, vous pouvez omettre le `[MPL]` suffixe.

Pour plus d'informations sur l'utilisation de pip pour installer et mettre à niveau les packages, consultez [Installation des packages](https://packaging.python.org/tutorials/installing-packages/).

 Kit SDK de chiffrement AWS pour Python Nécessite la [bibliothèque de cryptographie](https://cryptography.io/en/latest/) (pyca/cryptography) sur toutes les plateformes. Toutes les versions de installent et compilent `pip` automatiquement la `cryptography` bibliothèque sous Windows. `pip`8.1 et versions ultérieures s'installent et se compilent automatiquement sous `cryptography` Linux. Si vous utilisez une version antérieure de `pip` et que votre environnement Linux ne dispose pas des outils nécessaires pour créer la `cryptography` bibliothèque, vous devez les installer. Pour de plus amples informations, veuillez consulter [Building cryptography on Linux](https://cryptography.io/en/latest/installation.html#building-cryptography-on-linux).

Les versions 1.10.0 et 2.5.0 de la norme situent la Kit SDK de chiffrement AWS pour Python dépendance [cryptographique](https://cryptography.io/en/latest/) entre 2.5.0 et 3.3.2. Les autres versions Kit SDK de chiffrement AWS pour Python installent la dernière version de cryptographie. Si vous avez besoin d'une version de cryptographie ultérieure à la version 3.3.2, nous vous recommandons d'utiliser la dernière version majeure du. Kit SDK de chiffrement AWS pour Python

Pour obtenir la dernière version de développement du Kit SDK de chiffrement AWS pour Python, accédez au [aws-encryption-sdk-python](https://github.com/aws/aws-encryption-sdk-python/)référentiel dans GitHub.

Après avoir installé le Kit SDK de chiffrement AWS pour Python, commencez par consulter l'[exemple de code Python présenté](python-example-code.md) dans ce guide.

# Kit SDK de chiffrement AWS pour Python exemple de code
<a name="python-example-code"></a>

Les exemples suivants vous montrent comment utiliser le Kit SDK de chiffrement AWS pour Python pour chiffrer et déchiffrer des données.

Les exemples présentés dans cette section montrent comment utiliser la version 4. *x* du Kit SDK de chiffrement AWS pour Python avec la dépendance optionnelle de la [bibliothèque des fournisseurs de matériel cryptographique](https://github.com/aws/aws-cryptographic-material-providers-library) (`aws-cryptographic-material-providers`). Pour consulter des exemples utilisant des versions antérieures ou des installations sans la bibliothèque des fournisseurs de matériaux (MPL), recherchez votre version dans la liste des [versions](https://github.com/aws/aws-encryption-sdk-python/releases) du [aws-encryption-sdk-python](https://github.com/aws/aws-encryption-sdk-python/)référentiel sur GitHub.

Lorsque vous utilisez la version 4. *x* du Kit SDK de chiffrement AWS pour Python avec le MPL, il utilise des trousseaux de [clés pour chiffrer](choose-keyring.md) les [enveloppes.](concepts.md#envelope-encryption) AWS Encryption SDK Il fournit des porte-clés compatibles avec les fournisseurs de clés principales que vous utilisiez dans les versions précédentes. Pour de plus amples informations, veuillez consulter [Compatibilité du porte-clés](choose-keyring.md#keyring-compatibility). Pour des exemples de migration depuis des fournisseurs de clés principales vers des porte-clés, voir [Exemples de migration](https://github.com/aws/aws-encryption-sdk-python/tree/master/examples/src/migration) dans le `aws-encryption-sdk-python` référentiel sur ; GitHub

**Topics**
+ [Chaînes](#python-example-strings)
+ [Flux d'octets](#python-example-streams)

## Chiffrement et déchiffrement de chaînes
<a name="python-example-strings"></a>

L'exemple suivant montre comment utiliser le AWS Encryption SDK pour chiffrer et déchiffrer des chaînes. Cet exemple utilise un [AWS KMS trousseau de clés](use-kms-keyring.md) avec une clé KMS de chiffrement symétrique.

Cet exemple instancie le AWS Encryption SDK client avec la [politique d'engagement par défaut](migrate-commitment-policy.md),. `REQUIRE_ENCRYPT_REQUIRE_DECRYPT` Pour de plus amples informations, veuillez consulter [Définition de votre politique d'engagement](migrate-commitment-policy.md).

```
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
This example sets up the KMS Keyring

The AWS KMS keyring uses symmetric encryption KMS keys to generate, encrypt and
decrypt data keys. This example creates a KMS Keyring and then encrypts a custom input EXAMPLE_DATA
with an encryption context. This example also includes some sanity checks for demonstration:
1. Ciphertext and plaintext data are not the same
2. Encryption context is correct in the decrypted message header
3. Decrypted plaintext value matches EXAMPLE_DATA
These sanity checks are for demonstration in the example only. You do not need these in your code.

AWS KMS keyrings can be used independently or in a multi-keyring with other keyrings
of the same or a different type.

"""

import boto3
from aws_cryptographic_material_providers.mpl import AwsCryptographicMaterialProviders
from aws_cryptographic_material_providers.mpl.config import MaterialProvidersConfig
from aws_cryptographic_material_providers.mpl.models import CreateAwsKmsKeyringInput
from aws_cryptographic_material_providers.mpl.references import IKeyring
from typing import Dict  # noqa pylint: disable=wrong-import-order

import aws_encryption_sdk
from aws_encryption_sdk import CommitmentPolicy

EXAMPLE_DATA: bytes = b"Hello World"


def encrypt_and_decrypt_with_keyring(
    kms_key_id: str
):
    """Demonstrate an encrypt/decrypt cycle using an AWS KMS keyring.

    Usage: encrypt_and_decrypt_with_keyring(kms_key_id)
    :param kms_key_id: KMS Key identifier for the KMS key you want to use for encryption and
    decryption of your data keys.
    :type kms_key_id: string
    
    """
    # 1. Instantiate the encryption SDK client.
    # This builds the client with the REQUIRE_ENCRYPT_REQUIRE_DECRYPT commitment policy,
    # which enforces that this client only encrypts using committing algorithm suites and enforces
    # that this client will only decrypt encrypted messages that were created with a committing
    # algorithm suite.
    # This is the default commitment policy if you were to build the client as
    # `client = aws_encryption_sdk.EncryptionSDKClient()`.
    client = aws_encryption_sdk.EncryptionSDKClient(
        commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
    )

    # 2. Create a boto3 client for KMS.
    kms_client = boto3.client('kms', region_name="us-west-2")

    # 3. Optional: create encryption context.
    # Remember that your encryption context is NOT SECRET.
    encryption_context: Dict[str, str] = {
        "encryption": "context",
        "is not": "secret",
        "but adds": "useful metadata",
        "that can help you": "be confident that",
        "the data you are handling": "is what you think it is",
    }

    # 4. Create your keyring
    mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(
        config=MaterialProvidersConfig()
    )

    keyring_input: CreateAwsKmsKeyringInput = CreateAwsKmsKeyringInput(
        kms_key_id=kms_key_id,
        kms_client=kms_client
    )

    kms_keyring: IKeyring = mat_prov.create_aws_kms_keyring(
        input=keyring_input
    )

    # 5. Encrypt the data with the encryptionContext.
    ciphertext, _ = client.encrypt(
        source=EXAMPLE_DATA,
        keyring=kms_keyring,
        encryption_context=encryption_context
    )

    # 6. Demonstrate that the ciphertext and plaintext are different.
    # (This is an example for demonstration; you do not need to do this in your own code.)
    assert ciphertext != EXAMPLE_DATA, \
        "Ciphertext and plaintext data are the same. Invalid encryption"

    # 7. Decrypt your encrypted data using the same keyring you used on encrypt.
    plaintext_bytes, _ = client.decrypt(
        source=ciphertext,
        keyring=kms_keyring,
        # Provide the encryption context that was supplied to the encrypt method
        encryption_context=encryption_context,
    )

    # 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
    # (This is an example for demonstration; you do not need to do this in your own code.)
    assert plaintext_bytes == EXAMPLE_DATA, \
        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
```

## Chiffrement et déchiffrement de flux d'octets
<a name="python-example-streams"></a>

L'exemple suivant montre comment utiliser le AWS Encryption SDK pour chiffrer et déchiffrer des flux d'octets. Cet exemple utilise un trousseau de [clés AES brut](use-raw-aes-keyring.md).

Cet exemple instancie le AWS Encryption SDK client avec la [politique d'engagement par défaut](migrate-commitment-policy.md),. `REQUIRE_ENCRYPT_REQUIRE_DECRYPT` Pour de plus amples informations, veuillez consulter [Définition de votre politique d'engagement](migrate-commitment-policy.md).

```
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
This example demonstrates file streaming for encryption and decryption.

File streaming is useful when the plaintext or ciphertext file/data is too large to load into
memory. Therefore, the AWS Encryption SDK allows users to stream the data, instead of loading it
all at once in memory. In this example, we demonstrate file streaming for encryption and decryption
using a Raw AES keyring. However, you can use any keyring with streaming.

This example creates a Raw AES Keyring and then encrypts an input stream from the file
`plaintext_filename` with an encryption context to an output (encrypted) file `ciphertext_filename`.
It then decrypts the ciphertext from `ciphertext_filename` to a new file `decrypted_filename`.
This example also includes some sanity checks for demonstration:
1. Ciphertext and plaintext data are not the same
2. Encryption context is correct in the decrypted message header
3. Decrypted plaintext value matches EXAMPLE_DATA
These sanity checks are for demonstration in the example only. You do not need these in your code.

See raw_aes_keyring_example.py in the same directory for another raw AES keyring example
in the AWS Encryption SDK for Python.
"""
import filecmp
import secrets

from aws_cryptographic_material_providers.mpl import AwsCryptographicMaterialProviders
from aws_cryptographic_material_providers.mpl.config import MaterialProvidersConfig
from aws_cryptographic_material_providers.mpl.models import AesWrappingAlg, CreateRawAesKeyringInput
from aws_cryptographic_material_providers.mpl.references import IKeyring
from typing import Dict  # noqa pylint: disable=wrong-import-order

import aws_encryption_sdk
from aws_encryption_sdk import CommitmentPolicy


def encrypt_and_decrypt_with_keyring(
    plaintext_filename: str,
    ciphertext_filename: str,
    decrypted_filename: str
):
    """Demonstrate a streaming encrypt/decrypt cycle.

    Usage: encrypt_and_decrypt_with_keyring(plaintext_filename
                                            ciphertext_filename
                                            decrypted_filename)
    :param plaintext_filename: filename of the plaintext data
    :type plaintext_filename: string
    :param ciphertext_filename: filename of the ciphertext data
    :type ciphertext_filename: string
    :param decrypted_filename: filename of the decrypted data
    :type decrypted_filename: string
    """
    # 1. Instantiate the encryption SDK client.
    # This builds the client with the REQUIRE_ENCRYPT_REQUIRE_DECRYPT commitment policy,
    # which enforces that this client only encrypts using committing algorithm suites and enforces
    # that this client will only decrypt encrypted messages that were created with a committing
    # algorithm suite.
    # This is the default commitment policy if you were to build the client as
    # `client = aws_encryption_sdk.EncryptionSDKClient()`.
    client = aws_encryption_sdk.EncryptionSDKClient(
        commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
    )

    # 2. The key namespace and key name are defined by you.
    # and are used by the Raw AES keyring to determine
    # whether it should attempt to decrypt an encrypted data key.
    key_name_space = "Some managed raw keys"
    key_name = "My 256-bit AES wrapping key"

    # 3. Optional: create encryption context.
    # Remember that your encryption context is NOT SECRET.
    encryption_context: Dict[str, str] = {
        "encryption": "context",
        "is not": "secret",
        "but adds": "useful metadata",
        "that can help you": "be confident that",
        "the data you are handling": "is what you think it is",
    }

    # 4. Generate a 256-bit AES key to use with your keyring.
    # In practice, you should get this key from a secure key management system such as an HSM.

    # Here, the input to secrets.token_bytes() = 32 bytes = 256 bits
    static_key = secrets.token_bytes(32)

    # 5. Create a Raw AES keyring
    # We choose to use a raw AES keyring, but any keyring can be used with streaming.
    mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(
        config=MaterialProvidersConfig()
    )

    keyring_input: CreateRawAesKeyringInput = CreateRawAesKeyringInput(
        key_namespace=key_name_space,
        key_name=key_name,
        wrapping_key=static_key,
        wrapping_alg=AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16
    )

    raw_aes_keyring: IKeyring = mat_prov.create_raw_aes_keyring(
        input=keyring_input
    )

    # 6. Encrypt the data stream with the encryptionContext
    with open(plaintext_filename, 'rb') as pt_file, open(ciphertext_filename, 'wb') as ct_file:
        with client.stream(
            mode='e',
            source=pt_file,
            keyring=raw_aes_keyring,
            encryption_context=encryption_context
        ) as encryptor:
            for chunk in encryptor:
                ct_file.write(chunk)

    # 7. Demonstrate that the ciphertext and plaintext are different.
    # (This is an example for demonstration; you do not need to do this in your own code.)
    assert not filecmp.cmp(plaintext_filename, ciphertext_filename), \
        "Ciphertext and plaintext data are the same. Invalid encryption"

    # 8. Decrypt your encrypted data stream using the same keyring you used on encrypt.
    with open(ciphertext_filename, 'rb') as ct_file, open(decrypted_filename, 'wb') as pt_file:
        with client.stream(
            mode='d',
            source=ct_file,
            keyring=raw_aes_keyring,
            encryption_context=encryption_context
        ) as decryptor:
            for chunk in decryptor:
                pt_file.write(chunk)

    # 10. Demonstrate that the decrypted plaintext is identical to the original plaintext.
    # (This is an example for demonstration; you do not need to do this in your own code.)
    assert filecmp.cmp(plaintext_filename, decrypted_filename), \
        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
```