AWSのKMS(Key Management Service)を使ってみた。
KMSを使うと以下のようなことができて嬉しい。
- ソースコードに載せたくない情報(認証情報など)を暗号化できる
- 暗号化した鍵の管理をAWS側でやってくれる
やってみたこと
1. キーの作成
1. キーの作成
AWSコンソール画面 > IAM > 暗号化キー > キーの作成
からキーを作っておく
2. キーのAmazon Resource Nameをメモ
1.で作成したキーのリンクをクリックして、arn:aws:kms:xxxxxxxxxxxxxxのところをメモっておく
3. 検証に使うec2を起動
KMSにアクセスできるロールを適用したec2の起動する
4. 3.のロールから1.のキーのアクセスを許可
AWSコンソール画面 > IAM > 暗号化キー > キーユーザー
4.の操作はec2ロールにアタッチしたポリシーに応じて必要だったり、不要だったりする。
- ec2にPowerUserAccessポリシーをつけていれば、3.の操作は不要。
- AWSKeyManagementServicePowerUserポリシーしかつけてない場合は、3.の操作が必要。
5. 検証用Pythonコードを実行
This file contains 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
import boto3 | |
class KmsHelper: | |
def __init__(self): | |
self._client = boto3.client('kms') | |
def encrypt(self, key_id, plain_text): | |
response = self._client.encrypt(KeyId=key_id, Plaintext=plain_text) | |
return response['CiphertextBlob'] | |
def decrypt(self, cipher_text): | |
response = self._client.decrypt(CiphertextBlob=cipher_text) | |
return response['Plaintext'] | |
def main(): | |
key_id = 'arn:aws:kms:xxxxxxxxxxxxxxxxxxx' | |
plain_text = 'hello, world!' | |
helper = KmsHelper() | |
enc_text = helper.encrypt(key_id, plain_text) | |
dec_text = helper.decrypt(enc_text) | |
print(dec_text) # b'hello, world!' | |
if __name__ == '__main__': | |
main() |
注意事項
キーを作成したリージョンとキーを利用するリージョンが異なると以下のようなエラーがでるので注意。
botocore.errorfactory.NotFoundException: An error occurred (NotFoundException) when calling the Encrypt operation: Invalid arn