Created
July 12, 2016 01:26
-
-
Save hajimeni/2d5eb87a1cfd55f0ebb2077d8621772f to your computer and use it in GitHub Desktop.
Python3+boto3でKMSのdata-keyを利用して暗号化、復号化するサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # KMS流れ | |
| # 暗号化 | |
| # 1. masterkeyIdを使ってdatakeyを生成 | |
| # generate_data_key | |
| # 2. datakeyのPlainTextをキーにしてデータをEncrypt | |
| # Pycryptoとか | |
| # 3. datakeyのCiphertextBlobのBase64とEncryptoしたデータのBase64は保存 | |
| # 他のキーは破棄 | |
| # 復号化 | |
| 1. datakeyのCiphertextBlobのbytesを decryptでPlainTextにする。 | |
| 2. datakeyのPlainTextをキーにして、データのBytesをDecrypt(Pycrypt) | |
| plaintextは破棄。 | |
| import boto3 | |
| import base64 | |
| from Crypto.Cipher import AES | |
| client = boto3.client('kms') | |
| data_key = client.generate_data_key(KeyId='{UUID}',KeySpec='AES_256') | |
| secret = data_key['Plaintext'] | |
| message = "暗号化したい任意のテキスト" # utf-8のテキストデータ前提 | |
| aes = AES.new(secret) | |
| ## padding | |
| bs = AES.block_size | |
| data = message.encode('utf-8') | |
| padding_length = (bs - len(data) % bs) or bs | |
| data += "".rjust(padding_length, "\x00").encode("utf-8") # \x00パディングをしているので、バイナリの場合はbase64してからとかじゃないとダメ。 | |
| encrypt_data = aes.encrypt(data) | |
| ## 保存すべきデータ | |
| ## - CiphertextBlob = data_key['CiphertextBlob'] | |
| ## - encrypt_data | |
| ## Decrypt | |
| import boto3 | |
| import base64 | |
| from Crypto.Cipher import AES | |
| client = boto3.client('kms') | |
| secret = client.decrypt(CiphertextBlob=data_key['CiphertextBlob']) | |
| data = encrypto_data | |
| aes = AES.new(secret) | |
| decrypt_data = aes.decrypt(data) | |
| data = decrypt_data.decode('utf-8').rstrip('\x00') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment