すべてのプロダクト
Search
ドキュメントセンター

Key Management Service:Python用暗号化SDKを使い始める

最終更新日:Dec 18, 2024

Encryption SDKは、Key Management Service (KMS) とともに使用されるクライアント側の暗号化ライブラリで、データの暗号化と復号化、データの署名と署名の検証を行います。 このトピックでは、Encryption SDK for Python 3を使用してデータを暗号化および復号化する方法について説明します。

背景情報

Encryption SDK For Pythonのサンプルコードの詳細については、alibabacloud-encryption-sdk-pythonをご参照ください。

説明

Alibaba CloudアカウントのAccessKeyペアには、すべてのAPI操作に対する権限があります。 AccessKeyペアを使用して操作を実行することは、リスクの高い操作です。 RAMユーザーを使用してAPI操作を呼び出したり、ルーチンのO&Mを実行することを推奨します。プロジェクトコードにAccessKey IDとAccessKey Secretを保存しないことを推奨します。 そうしないと、AccessKeyペアが漏洩し、アカウントに属するすべてのリソースのセキュリティが侵害される可能性があります。

この例では、AccessKeyペアは、ID認証を実装するためにALIBABA_CLOUD_ACCESS_KEY_IDとALIBABA_CLOUD_ACCESS_KEY_SECRET環境変数に保存されます。

オンプレミスマシンに暗号化SDKをインストールする

  1. Encryption SDKをインストールします。

    git clone https://github.com/aliyun/alibabacloud-encryption-sdk-python.git
    cd alibabacloud-encryption-sdk-python
    python setup.py install
  2. Encryption SDKのバージョンを確認します。

    1. 次のコマンドを実行してPython環境に入ります。

      python
    2. 次のコマンドを実行して、Encryption SDKのバージョンを確認します。

      import aliyun_encryption_sdk
      aliyun_encryption_sdk.__version__

      コマンドを実行すると、Pythonコンソールにバージョン番号「0.1.1」が表示されます。

バイト配列型のデータの暗号化と復号化

# -*- coding: UTF-8 -*-
"""Example showing basic encryption and decryption."""

import base64
import os

from aliyun_encryption_sdk.cache.local import LocalDataKeyMaterialCache
from aliyun_encryption_sdk.ckm.cache import CachingCryptoKeyManager
from aliyun_encryption_sdk.client import AliyunCrypto
from aliyun_encryption_sdk.kms import AliyunConfig
from aliyun_encryption_sdk.provider.default import DefaultDataKeyProvider


def build_aliyun_crypto(cache=False):
    config = AliyunConfig(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
    client = AliyunCrypto(config)
    if cache:
        client.crypto_key_manager = CachingCryptoKeyManager(LocalDataKeyMaterialCache(), 5)
    return client


def encrypt_sample():
    print("Plaintext: " + PLAIN_TEXT)
    provider = DefaultDataKeyProvider(AES_KEY_ARN)
    client = build_aliyun_crypto(False)
    cipher_text, enc_material = client.encrypt(provider, PLAIN_TEXT.encode("utf-8"), ENCRYPTION_CONTEXT)
    cipher_text_str = base64.standard_b64encode(cipher_text).decode("utf-8")
    print(u"Ciphertext: " + cipher_text_str)
    return cipher_text_str


def decrypt_sample(cipher_text):
    cipher_text_bytes = base64.standard_b64decode(cipher_text.encode("utf-8"))
    provider = DefaultDataKeyProvider(AES_KEY_ARN)
    client = build_aliyun_crypto(False)
    plain_text, dec_material = client.decrypt(provider, cipher_text_bytes)
    print(u"Decryption result: " + bytes.de code(plain_text))
    return plain_text


if __name__ == '__main__':
    PLAIN_TEXT = "some plaintext"
    ACCESS_KEY_ID = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    ACCESS_KEY_SECRET = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    AES_KEY_ARN = os.getenv("AES_KEY_ARN")
    ENCRYPTION_CONTEXT = {
        "this": "context",
        "can help you": "to confirm",
        "this data": "is your original data"
    }
    cipherText = encrypt_sample()
    decrypt_sample(cipherText)

バイトストリーム型のデータの暗号化と復号化

# -*- coding: UTF-8 -*-
"""Example showing basic encryption and decryption."""

import os

from aliyun_encryption_sdk.cache.local import LocalDataKeyMaterialCache
from aliyun_encryption_sdk.ckm.cache import CachingCryptoKeyManager
from aliyun_encryption_sdk.client import AliyunCrypto
from aliyun_encryption_sdk.kms import AliyunConfig
from aliyun_encryption_sdk.provider.default import DefaultDataKeyProvider


def build_aliyun_crypto(cache=False):
    config = AliyunConfig(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
    client = AliyunCrypto(config)
    if cache:
        client.crypto_key_manager = CachingCryptoKeyManager(LocalDataKeyMaterialCache(), 5)
    return client


def file_stream_sample():
    origin_file_path = r"some_file"
    encrypted_file_path = r"enc_file"
    decrypted_file_path = r"dec_file"
    provider = DefaultDataKeyProvider(AES_KEY_ARN)
    client = build_aliyun_crypto()
    with open(origin_file_path, "rb") as f, open(encryped_file_path, "wb") as cipher_text:
        encrypted_stream, _ = client.encrypt_stream(provider, f)
        with encrypted_stream as stream:
            for content in stream:
                cipher_text.write(content)

    with open(encryped_file_path, "rb") as f, open(decrypted_file_path, "wb") as plain_text:
        decrypted_stream, _ = client.decrypt_stream(provider, f)
        with decrypted_stream as stream:
            for content in stream:
                plain_text.write(content)


if __name__ == '__main__':
    ACCESS_KEY_ID = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    ACCESS_KEY_SECRET = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    AES_KEY_ARN = os.getenv("AES_KEY_ARN")
    file_stream_sample()