LoginSignup
9
6

More than 3 years have passed since last update.

AWS DynamoDB + pythonで暗号化&復号にハマった話

Last updated at Posted at 2017-12-29

やりたいこと

①pythonで引数をkmsで暗号化してdynamoDBにぶちこむ。

②ぶちこまれた値を取り出して復号してふにゃふにゃする。

①はできたよ

ここを参考にしてできたよ
http://blog.suz-lab.com/2015/10/lambdapythonkmssqs.html

(引数keyで与えた項目を暗号化して、tableテーブルのkeyにいれる)

set.py
import boto3
from boto3.session import Session
from boto3.dynamodb.conditions import Key, Attr
import base64

# lambdaからはこっち
try:
    kms = boto3.client('kms')  
    dynamodb = boto3.resource('dynamodb')
except:
# 手元からはこっち
    kms = session.client('kms')    
    dynamodb = session.resource('dynamodb')

table= dynamodb.Table('table')
keyId = 'key'

def lambda_handler(event, context):
    key = base64.b64encode(kms.encrypt(KeyId = keyId,Plaintext = event['key'])['CiphertextBlob'])            
    response = table.put_item(Item={'key':key})
    return response

復号にはまる

あとは取り出して復号すればいいのねーと思いきや、取り出したるは意味不明なboto3.dynamodb.types.Binary型

様々なバイナリエンコードをごり押して、最終的にreprで文字列化⇒replaceできれいに整形⇒b64でBytes型に⇒復号⇒utf-8でdecodeをして復号した文字列をゲッツ
(2018/3/11 追記)boto3.dynamodb.types.Binary.valueで取り出したBytesを復号してutf-8 でdecodeで文字列をゲッツできます!これならきもいreplaceなど不要!

get.py

import boto3
from boto3.session import Session
from boto3.dynamodb.conditions import Key, Attr
import base64

# lambdaからはこっち
try:
    kms = boto3.client('kms')  
    dynamodb = boto3.resource('dynamodb')
except:
# 手元からはこっち
    kms = session.client('kms')    
    dynamodb = session.resource('dynamodb')

table= dynamodb.Table('table')

def lambda_handler(event, context):
    beforekey = table.get_item(Key={'key': event['key']})
    afterkey = kms.decrypt(CiphertextBlob=base64.b64decode(beforekey['Item']['key'].value)['Plaintext'].decode()
    ikasuFunction(afterkey)

def ikasuFunction(key):
    # hoge

情報モトム

いいやり方あったら教えてください

9
6
4

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
9
6