

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS Encryption SDK for Python
<a name="python"></a>

このトピックでは、 AWS Encryption SDK for Pythonをインストールして使用する方法について説明します。を使用したプログラミングの詳細については AWS Encryption SDK for Python、GitHub の [aws-encryption-sdk-python](https://github.com/aws/aws-encryption-sdk-python/) リポジトリを参照してください。API のドキュメントについては、[Read the Docs](https://aws-encryption-sdk-python.readthedocs.io/en/latest/) を参照してください。

**Topics**
+ [

## 前提条件
](#python-prerequisites)
+ [

## インストール
](#python-installation)
+ [例](python-example-code.md)

## 前提条件
<a name="python-prerequisites"></a>

をインストールする前に AWS Encryption SDK for Python、次の前提条件を満たしていることを確認してください。

**Python のサポートされているバージョン**  
 AWS Encryption SDK for Python バージョン 3.2.0 以降では、Python 3.8 以降が必要です。  
[AWS 暗号化マテリアルプロバイダーライブラリ](https://github.com/aws/aws-cryptographic-material-providers-library) (MPL) は、バージョン 4.*x* で AWS Encryption SDK for Python 導入された のオプション依存関係です。MPL をインストールする場合は、Python 3.11 以降を使用する必要があります。
以前のバージョンの は Python 2.7 および Python 3.4 以降 AWS Encryption SDK をサポートしていますが、最新バージョンの を使用することをお勧めします AWS Encryption SDK。  
Python をダウンロードするには、「[Python のダウンロード](https://www.python.org/downloads/)」を参照してください。

**Python 用 pip インストールツール**  
`pip` は、Python 3.6 以降のバージョンには含まれていますが、アップグレードすることをお勧めします。`pip` のアップグレードまたはインストールの詳細については、「`pip` ドキュメント」の「[インストール](https://pip.pypa.io/en/latest/installation/)」を参照してください。

## インストール
<a name="python-installation"></a>

 AWS Encryption SDK for Pythonの最新バージョンをインストールします。

**注記**  
3.0.0 より AWS Encryption SDK for Python 前の のすべてのバージョンは[end-of-supportフェーズ](https://docs.aws.amazon.com/sdkref/latest/guide/maint-policy.html#version-life-cycle)にあります。  
バージョン 2.0.x 以降から AWS Encryption SDK の最新バージョンにコードやデータを変更せずに安全に更新できます。ただし、バージョン 2.0.x で導入された[新しいセキュリティ機能](about-versions.md#version-2)には下位互換性がありません。1.7.x より前のバージョンから 2.0.x 以降のバージョンに更新するには、まず AWS Encryption SDKの最新の 1.x バージョンに更新する必要があります。詳細については、「[の移行 AWS Encryption SDK](migration.md)」を参照してください。

次の例に示すように AWS Encryption SDK for Python、 `pip`を使用して をインストールします。

**最新バージョンをインストールするには**  

```
pip install "aws-encryption-sdk[MPL]"
```
`[MPL]` サフィックスは、[AWS 暗号化マテリアルプロバイダーライブラリ (MPL) をインストールします](https://github.com/aws/aws-cryptographic-material-providers-library)。MPL には、データを暗号化および復号するためのコンストラクトが含まれています。MPL は、バージョン 4.*x* で AWS Encryption SDK for Python 導入された のオプション依存関係です。MPL のインストールを強くお勧めします。ただし、MPL を使用する予定がない場合は、`[MPL]`サフィックスを省略できます。

pip を使用してパッケージをインストールおよびアップグレードする方法の詳細については、「[パッケージのインストール](https://packaging.python.org/tutorials/installing-packages/)」を参照してください。

では、すべてのプラットフォームで[暗号化ライブラリ](https://cryptography.io/en/latest/) (pyca/cryptography) AWS Encryption SDK for Python が必要です。`pip` のすべてのバージョンでは、Windows に `cryptography` ライブラリがインストールされて構築されます。`pip` 8.1 以降では、Linux に `cryptography` が自動的にインストールされて構築されます。以前のバージョンの `pip` を使用していて、Linux 環境に、`cryptography` ライブラリを構築するために必要なツールがない場合は、それらをインストールする必要があります。詳細については、「[Building cryptography on Linux](https://cryptography.io/en/latest/installation.html#building-cryptography-on-linux)」を参照してください。

バージョン 1.10.0 と 2.5.0 は、2.5.0 と 3.3.2 の間の[暗号化](https://cryptography.io/en/latest/)依存関係 AWS Encryption SDK for Python を固定します。の他のバージョンでは、最新バージョンの暗号化 AWS Encryption SDK for Python がインストールされます。3.3.2 以降の暗号化のバージョンが必要な場合は、 AWS Encryption SDK for Pythonの最新のメジャーバージョンを使用することを推奨します。

の最新バージョンについては AWS Encryption SDK for Python、GitHub の [aws-encryption-sdk-python](https://github.com/aws/aws-encryption-sdk-python/) リポジトリを参照してください。

をインストールしたら AWS Encryption SDK for Python、このガイドの [Python サンプルコード](python-example-code.md)を参照して開始します。

# AWS Encryption SDK for Python サンプルコード
<a name="python-example-code"></a>

次の例は、 AWS Encryption SDK for Python を使用してデータを暗号化および復号する方法を示しています。

このセクションの例では、オプションの[暗号化マテリアルプロバイダーライブラリ](https://github.com/aws/aws-cryptographic-material-providers-library)の依存関係 () AWS Encryption SDK for Python で のバージョン 4.*x* を使用する方法を示します`aws-cryptographic-material-providers`。以前のバージョンを使用する例、またはマテリアルプロバイダーライブラリ (MPL) を使用しないインストールを表示するには、GitHub の [aws-encryption-sdk-python](https://github.com/aws/aws-encryption-sdk-python/) リポジトリの[リリース](https://github.com/aws/aws-encryption-sdk-python/releases)リストでリリースを検索します。

MPL AWS Encryption SDK for Python で のバージョン 4.*x* を使用する場合、[キーリング](choose-keyring.md)を使用して[エンベロープ暗号化](concepts.md#envelope-encryption)を実行します。 AWS Encryption SDK には、以前のバージョンで使用していたマスターキープロバイダーと互換性のあるキーリングが用意されています。詳細については、「[キーリングの互換性](choose-keyring.md#keyring-compatibility)」を参照してください。マスターキープロバイダーからキーリングへの移行の例については、GitHub の `aws-encryption-sdk-python`リポジトリの[「移行の例](https://github.com/aws/aws-encryption-sdk-python/tree/master/examples/src/migration)」を参照してください。

**Topics**
+ [文字列](#python-example-strings)
+ [バイトストリーム](#python-example-streams)

## 文字列の暗号化と復号
<a name="python-example-strings"></a>

次の例は、 を使用して文字列 AWS Encryption SDK を暗号化および復号する方法を示しています。この例では、対称暗号化 KMS キーを持つ キー[AWS KMS リング](use-kms-keyring.md)を使用します。

この例では、[デフォルトのコミットメントポリシー](migrate-commitment-policy.md) を使用して AWS Encryption SDK クライアントをインスタンス化します`REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。詳細については、「[コミットメントポリシーの設定](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"
```

## バイトストリームの暗号化と復号
<a name="python-example-streams"></a>

次の例は、 を使用してバイトストリーム AWS Encryption SDK を暗号化および復号する方法を示しています。この例では、[Raw AES キーリング](use-raw-aes-keyring.md)を使用します。

この例では、[デフォルトのコミットメントポリシー](migrate-commitment-policy.md) を使用して AWS Encryption SDK クライアントをインスタンス化します`REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。詳細については、「[コミットメントポリシーの設定](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"
```