1
0

AWSのPython sdkを使ってKMSの暗号化複号化を試した

Posted at

やりたいこと

AWSのマネコンじゃなく、プログラムでKMSの暗号化をやりたい

前提

・Pythonインストール済み
・AWS-CLIインストール済み
・ローカル上、AWSのアクセス情報設定済み

やり方

さっそくですが、調べた結果を共有します~
今回はすでにKMSにあるKeyIdを使うため、プログラム上はKeyを作成せずに直接暗号化・複号化をします

import boto3
import base64

# AWS KMS クライアントの初期化
kms_client = boto3.client('kms')

# 暗号化する平文データ
plaintext = "password"

# 暗号化
response = kms_client.encrypt(
    KeyId='arn:aws:kms:ap-northeast-1:xxxxx:key/xxxxxx',  # 実際のキー ID に置き換えてください
    Plaintext=plaintext.encode()
)
# これがまだbyte (byte64)形式
ciphertext_blob = response['CiphertextBlob']

# byte (byte64)をstrにする
ciphertext_blob = base64.b64encode(ciphertext_blob).decode('utf-8')

# 結果の表示
print(f"Encrypted text: {ciphertext_blob}")

# 復号化
# まずstrをbyte (byte64)に戻す
decrypt_response = kms_client.decrypt(
    CiphertextBlob=base64.b64decode(ciphertext_blob)
)
decrypted_text = decrypt_response['Plaintext'].decode()

# 結果の表示
print(f"Decrypted text: {decrypted_text}")

終わりに

業務上、Pythonでの暗号化・複号化をいろいろ試し、FernetやCryptoを使ってみたが、最後お客様から「KMSでやりたい~」となったので、慌ててKMSを調査に入り、無事期日内で実装できてよかった!

今回を機に、暗号化複号化の仕組みについて理解が深まって個人的にはいい経験だったので、調べた内容をブログとして残したいと思った!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0