AWS 서명 V4로 DynamoDB에 테이블 만들기

15974 단어 DynamoDBAWS
아래를 참고로 작성한 샘플입니다.

htps : // / cs. 아 ws. 아마존. 이 m / 그럼 _ jp / 게네라 l / ㅁ st / gr / ㅇ gv4 ー ぁ ぁ ぁ ぁ ぁ ぇ s. HTML

프로그램



python.py
## coding: UTF-8

import sys, os, base64, datetime, hashlib, hmac 
import requests # pip install requests

# 初期設定
access_key = '【TODO アクセスキーを入力してね!!!!!】'
secret_key = '【TODO シークレットキーを入力してね!!!!!】'

service = 'dynamodb'
host = 'dynamodb.ap-northeast-1.amazonaws.com'
canonical_uri = '/'
signed_headers = 'content-type;host;x-amz-date;x-amz-target'
region = 'ap-northeast-1'
endpoint = 'https://dynamodb.ap-northeast-1.amazonaws.com/'
algorithm = 'AWS4-HMAC-SHA256'
content_type = 'application/x-amz-json-1.0'
amz_target = 'DynamoDB_20120810.CreateTable'
request_parameters =  '{'
request_parameters +=  '"KeySchema": [{"KeyType": "HASH","AttributeName": "Id"}],'
request_parameters +=  '"TableName": "TestTable2","AttributeDefinitions": [{"AttributeName": "Id","AttributeType": "S"}],'
request_parameters +=  '"ProvisionedThroughput": {"WriteCapacityUnits": 5,"ReadCapacityUnits": 5}'
request_parameters +=  '}'
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
date_stamp = t.strftime('%Y%m%d')
canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n' + 'x-amz-target:' + amz_target + '\n'

# ************* 変換関数/ *************

# (参考)※文字列をバイト列に変換(encode)してハッシュ値を取得

#sha256メッセージダイジェスト取得
def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()

#sha256メッセージダイジェスト取得(hex)
def hmac_sha256_hex(key, msg):
    return hmac.new(key, msg, hashlib.sha256).hexdigest()

#sha256ハッシュ値を取得
def hash_sha256(byteValue):
    #hashlib.sha256の引数はバイトのみ。
    return hashlib.sha256(byteValue).hexdigest()

# ************* /変換関数 *************


def getSignatureKey(key, date_stamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning



# ************* 【1】正規リクエスト作成 *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html

# ①httpメソッド設定
method = 'POST'

# ②URI設定(※ドメイン以降) 
#  ※設定済み(canonical_uri)

# ③クエリストリング設定
canonical_querystring = ''

# ④httpヘッダ設定
#  ※設定済み(canonical_headers)

# ⑤ヘッダ名リスト設定
#  ※設定済み(signed_headers)

# ⑥リクエスト本文のハッシュ値の取得 ★※文字列をバイト列に変換(encode)して渡す
payload_hash = hash_sha256(request_parameters.encode('utf-8'))

# ⑦正規リクエストの作成
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash



# ************* 【2】署名文字列作成 *************
#①アルゴリズム設定
#  ※設定済み(algorithm)

#②スコープ設定
credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'

#③署名作成  ★※文字列をバイト列に変換(encode)して渡す
string_to_sign = algorithm + '\n' +  amz_date + '\n' +  credential_scope + '\n' +  hash_sha256(canonical_request.encode('utf-8'))



# ************* 【③】署名計算 *************
#①署名キー設定
signing_key = getSignatureKey(secret_key, date_stamp, region, service)

#②署名設定  ★※文字列をバイト列に変換(encode)して渡す
signature = hmac_sha256_hex(signing_key, (string_to_sign).encode('utf-8'))


# ************* ④リクエスト作成 *************
#①認証用ヘッダ設定
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

#②httpリクエストヘッダ設定
headers = {'Content-Type':content_type,
           'X-Amz-Date':amz_date,
           'X-Amz-Target':amz_target,
           'Authorization':authorization_header}

# ************* ⑤HTTPリクエスト *************
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL = ' + endpoint)


r = requests.post(endpoint, data=request_parameters, headers=headers)

print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)

실행 결과





좋은 웹페이지 즐겨찾기