Skip to content

Instantly share code, notes, and snippets.

@youyo
Created September 28, 2019 04:21
Show Gist options
  • Save youyo/752494541522f740aa3f1909349ed9d3 to your computer and use it in GitHub Desktop.
Save youyo/752494541522f740aa3f1909349ed9d3 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -u
# ENV
stream_name='aws_version4_signatures_test'
payload=`cat <<EOL
{"Data": "XzxkYXRhPl8x","PartitionKey": "partitionKey","StreamName": "${stream_name}"}
EOL
`
# Not modify
access_key_id="${AWS_ACCESS_KEY_ID}"
secret_access_key_id="${AWS_SECRET_ACCESS_KEY}"
request_datetime=`date -u +%Y%m%dT%H%M%SZ`
request_date=`date -u +%Y%m%d`
service='kinesis'
region='ap-northeast-1'
aws_kinesis_endpoint="${service}.${region}.amazonaws.com"
credential_scope="${request_date}/${region}/${service}/aws4_request"
target='Kinesis_20131202.PutRecord'
# Function
generate_payload_hash(){
echo -n ${payload} | openssl sha256 -hex | sed 's/(stdin)= //'
}
generate_hashed_canonical_request(){
local payload_hash=`generate_payload_hash`
local canonical_request="POST\n/\n\ncontent-type:application/x-amz-json-1.1\nhost:${aws_kinesis_endpoint}\nx-amz-date:${request_datetime}\nx-amz-target:${target}\n\ncontent-type;host;x-amz-date;x-amz-target\n${payload_hash}"
echo -en ${canonical_request} | openssl sha256 -hex | sed 's/(stdin)= //'
}
get_signature_key(){
s=`echo -n ${request_date} | openssl dgst -sha256 -hmac "AWS4${secret_access_key_id}" -hex | sed 's/(stdin)= //'`
s=`echo -n ${region} | openssl dgst -sha256 -mac HMAC -macopt hexkey:${s} -hex | sed 's/(stdin)= //'`
s=`echo -n ${service} | openssl dgst -sha256 -mac HMAC -macopt hexkey:${s} -hex | sed 's/(stdin)= //'`
s=`echo -n "aws4_request" | openssl dgst -sha256 -mac HMAC -macopt hexkey:${s} -hex | sed 's/(stdin)= //'`
echo -n ${s}
}
build_authorization_header(){
local hashed_canonical_request=`generate_hashed_canonical_request`
local string_to_sign="AWS4-HMAC-SHA256\n${request_datetime}\n${credential_scope}\n${hashed_canonical_request}"
local signing_key=`get_signature_key`
local signature=`echo -en ${string_to_sign} | openssl dgst -sha256 -mac HMAC -macopt hexkey:${signing_key} -hex | sed 's/(stdin)= //'`
echo -n "AWS4-HMAC-SHA256 Credential=${access_key_id}/${credential_scope}, SignedHeaders=content-type;host;x-amz-date;x-amz-target, Signature=${signature}"
}
main(){
curl -v -X POST \
-d "${payload}" \
-H "Content-Type: application/x-amz-json-1.1" \
-H "X-Amz-Date: ${request_datetime}" \
-H "X-Amz-Target: ${target}" \
-H "Authorization: `build_authorization_header`" \
"https://${aws_kinesis_endpoint}/"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment