LoginSignup
4
4

More than 5 years have passed since last update.

Pythonで文字列の暗号化と、AWS KMSを使ってみた

Posted at

Pythonの文字列暗号化についてのメモ
32文字の暗号化文字列を使います。簡易的な暗号化ならこれでよいと思います。AWSのKMS (Key Management Service) を使ってみました。暗号化文字列が不要で、仮にソースコードを丸ごと盗まれても復号化できません。

通常の暗号化

32文字の暗号化文字列を使って暗号と復号を行います。
シンプルに書きましたが何気に数時間ハマりました。

main.py
# pip install cryptography
from cryptography.fernet import Fernet
import base64
ENCRYPT_KEY = 'AB123456789012345678901234567890' #32
text = 'password'
f = Fernet(base64.b64encode(bytes(ENCRYPT_KEY,'utf-8')))

enc = f.encrypt(bytes(text,'utf-8')).decode('utf-8')
print('enc='+enc)
dec = f.decrypt(bytes(enc,'utf-8')).decode('utf-8')
print('dec='+dec) 

出力
enc=gAAAAABcCh4uGbXwAZqoxpW7we-HLyKq5kAKmBFxjoRR18XvwW7K_F3HvH8mVH_MtMiV925l_9VuqZa41_BJCcr_gY34eR8dTg==
dec=password

AWS KMS を使う

AWSのLambdaでパスワードをベタ書きしようと思いKMSを使ってみました。KMSは Key Management Service です。KMSを使うと暗号化文字列が不要になります。

lambda.py
import boto3
from boto3 import client
import base64
def lambda_handler(event, context):
keyId = 'arn:aws:kms:ap-northeast-1:1234xxxxxxxxxxxx'
text = 'password'
kms = boto3.client('kms')

enc = kms.encrypt(
    KeyId = keyId,
    Plaintext = text
)['CiphertextBlob']
enc = base64.b64encode(enc).decode('utf-8')
print('enc='+enc)

enc = base64.b64decode(enc)
dec = kms.decrypt(
    CiphertextBlob = enc
)['Plaintext'].decode('utf-8')
print('dec='+dec) 

出力
enc=AQICAHjj3VIPpSFJ97WdbTa7qxyHdfKCNkgKDmctakOr9kNWtwHGlz33dLnWmzlL9WXijF+eAAAAZjBkBgkqhkiG9w0BBwagVzBVAgEAMFAGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMMFj845J+zJoG5SaeAgEQgCPJivQXwReePpRRYLJwn3fgLfDrKlyy12X6fHck3ZkheNUZ3Q==
dec=password

実際使う場合は以下のようになります。たとえソースコードが流出してもこれだけでは復号できません。

lambda.py
import boto3
from boto3 import client
import base64
def lambda_handler(event, context):
keyId = 'arn:aws:kms:ap-northeast-1:1234xxxxxxxxxxxx'
text = 'AQICAHjj3VIPpSFJ97WdbTa7qxyHdfKCNkgKDmctakOr9kNWtwHGlz33dLnWmzlL9WXijF+eAAAAZjBkBgkqhkiG9w0BBwagVzBVAgEAMFAGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMMFj845J+zJoG5SaeAgEQgCPJivQXwReePpRRYLJwn3fgLfDrKlyy12X6fHck3ZkheNUZ3Q=='
kms = boto3.client('kms')
pw = kms.decrypt(
    CiphertextBlob = base64.b64decode(text)
)['Plaintext'].decode('utf-8')

まとめ

暗号化は盗まれたらどうしようと複雑になりがちですが、KMSを使うとシンプルにできそうです。

4
4
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
4
4