Python编写AWS Version 4 signing (AWS4-HMAC-SHA256) for execute-api
# AWS Version 4 signing example # DynamoDB API (CreateTable) # See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
# This version makes a POST request and passes request parameters
# in the body (payload) of the request. Auth information is passed in
# an Authorization header. # POST /dev/v1/user/associations/robots/3147C60040239620 HTTP/1.1
# X-Amz-Date: 20180502T073321Z
# Host: njc3321216.execute-api.us-east-1.amazonaws.com
# x-amz-security-token: AgoGb3JpZ2luENP//////////wEaCXVzLWVhc3QtMSKAAhZ6pzVklfasnpF7+uhEzpnvrRzgXRgFqXvrPWkjtJamALYtWvG0A9sYuKF+b2Jxpitq3UUoatmH1LJtOS3iSXM8RpjiElYd8OZMGqBs7o8Z/7QJV69NUYzKewcVwWrv1HJHGmwTUR/8Oqs7bI9KibLAJclCFBYMgodLd8eYW3m9Oq4kAudQBB7vVQ4hyiGErvwAayA5SqtIvpkr3tR19nH0o57BJHyVNXMuYOKzhPquzxMuuV/wv1XXPGeH+qZNT1a6XAhFZ0LdHmi9A2TgrrmJhlsjvCfsvSA3phBqJhiWNHuM1JHNFF6Vcwg+UV4FdY4qwHP82WPQjiamgiPasEkq9QQIKRAAGgwzMzM0NDAzODkyNDYiDAB/KfmZzmMqsJAwJirSBCTMCqIcagKhuyDzw+1dvIIckZKY5haYIoOB3siUUy7gj2JTTYhxH2GRUSFdPduM05hglqvDHS6L9SyUwctgQ+fBjRIur4k9YtBrWJBI+KFVMEV5UyMr91V0LAMmzQDJfLzIC7av7hEy9LJMNt4axZyrzfKgXqiW2dhmABbREvq/6oBQKIk4x7NbnmOqoCHPfna6Y1QMGXjzZmzG1UYY/u24cyaARnQrMVGmnEPK3hum8RY/Zf/0JlTmz3sapSiRPOhIiDBGg0Cu0mq/arPu1n/nhf6mWdFgWd2pRg3H1WUk5SUystQrBlr1CxnUqQeSEE+IQp9+0HhYdeaMXtEA1V4Ju6ET2p696TZrssxtcd+xoeHUdiq7Rer1QZx04abXVKLVsL0t5KyASNCfLQKbwNBm6su1n2tpqKxdGWt3PmHKTUicOxSpJ+7w7/VVAkyEg3xfCexb7+H2cdhcTKrMvp1225lHkbyW69dgUrdMREvXNyOpu2ludhRZNxZFICCBNKI4xpwZ1PcLq0Wr2H3Uln4GxCTIomx5a7An6dcW6bogzEYTGhZYzEhgTY7GbqAG59zLzJ/NtbZqmYQC4adWolh37OibYuRffkVsDXYFLpJ1qCAw+y7wnwYELCD4QX+VRSOpArYDnmaJp338RjqZSE593LIAR9CR3ihaFsUdFPzRX6LqHCQq7VWA+FVQJCsgHxlcU8+ShHcv0jh745ClcMwi4mCZl1fO1L9HupnobVCXodRwaXJ1ZSDGlSG/qr5BevbKn5KRybg7CHBgcIMwhMfkODDB06XXBQ==
# Content-type: application/json; charset=utf-8
# x-amz-content-sha256: d96401ecabf9143f5c90fe37ba177f0de647314bcfd49c698acb132f80749212
# Accept: application/json; charset=utf-8
# Authorization: AWS4-HMAC-SHA256 Credential=ASIAJCV4GTJQPYRAYKYQ/20180502/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=3bd5e785b3e5110bb4a53b375013ec6888a8fe51ff3f4fa2b05e17ce4457896b
# Content-Length: 46
# User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.0; Nexus 9 Build/NRD90M)
# Connection: Keep-Alive
# Accept-Encoding: gzip
#{"password": ":1:1525246193:5aR5eYKn6zsQ6vIp"} # {
# "credentials": {
# "SecretKey": "JJ+BouOzY53lEkJMuQ/w/PtWQaCgo32sEwzD4mw+",
# "SessionToken": "AgoGb3JpZ2luENP//////////wEaCXVzLWVhc3QtMSKAAhZ6pzVklfasnpF7+uhEzpnvrRzgXRgFqXvrPWkjtJamALYtWvG0A9sYuKF+b2Jxpitq3UUoatmH1LJtOS3iSXM8RpjiElYd8OZMGqBs7o8Z/7QJV69NUYzKewcVwWrv1HJHGmwTUR/8Oqs7bI9KibLAJclCFBYMgodLd8eYW3m9Oq4kAudQBB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144f5a",
# "AccessKeyId": "ASIAJCV4GTJQPYRAYKYQ"
# }
# } import sys, os, base64, datetime, hashlib, hmac
import requests # pip install requests # ************* REQUEST VALUES *************
method = 'POST'
service = 'execute-api'
host = 'njc3321216.execute-api.us-east-1.amazonaws.com'
region = 'us-east-1'
endpoint = 'https://njc3321216.execute-api.us-east-1.amazonaws.com'
amz_security_token = 'AgoGb3JpZ2luENP//////////wEaCXVzLWVhc3QtMSKAAhZ6pzVklfasnpF7+uhEzpnvrRzgXRgFqXvrPWkjtJamALYtWvG0A9sYuKF+b2Jxpitq3UUoatmH1LJtOS3iSXM8RpjiElYd8OZMGqBs7o8Z/7QJV69NUYzKewcVwWrv1HJHGmwTUR/8Oqs7bI9KibLAJclCFBYMgodLd8eYW3m9Oq4kAudQBB7vVQ4hyiGErvwAayA5SqtIvpkr3tR19nH0o57BJHyVNXMuYOKzhPquzxMuuV/wv1XXPGeH+qZNT1a6XAhFZ0LdHmi9A2TgrrmJhlsjvCfsvSA3phBqJhiWNHuM1JHNFF6Vcwg+UV4FdY4qwHP82WPQjiamgiPasEkq9QQIKRAAGgwzMzM0NDAzODkyNDYiDAB/KfmZzmMqsJAwJirSBCTMCqIcagKhuyDzw+1dvIIckZKY5haYIoOB3siUUy7gj2JTTYhxH2GRUSFdPduM05hglqvDHS6L9SyUwctgQ+fBjRIur4k9YtBrWJBI+KFVMEV5UyMr91V0LAMmzQDJfLzIC7av7hEy9LJMNt4axZyrzfKgXqiW2dhmABbREvq/6oBQKIk4x7NbnmOqoCHPfna6Y1QMGXjzZmzG1UYY/u24cyaARnQrMVGmnEPK3hum8RY/Zf/0JlTmz3sapSiRPOhIiDBGg0Cu0mq/arPu1n/nhf6mWdFgWd2pRg3H1WUk5SUystQrBlr1CxnUqQeSEE+IQp9+0HhYdeaMXtEA1V4Ju6ET2p696TZrssxtcd+xoeHUdiq7Rer1QZx04abXVKLVsL0t5KyASNCfLQKbwNBm6su1n2tpqKxdGWt3PmHKTUicOxSpJ+7w7/VVAkyEg3xfCexb7+H2cdhcTKrMvp1225lHkbyW69dgUrdMREvXNyOpu2ludhRZNxZFICCBNKI4xpwZ1PcLq0Wr2H3Uln4GxCTIomx5a7An6dcW6bogzEYTGhZYzEhgTY7GbqAG59zLzJ/NtbZqmYQC4adWolh37OibYuRffkVsDXYFLpJ1qCAw+y7wnwYELCD4QX+VRSOpArYDnmaJp338RjqZSE593LIAR9CR3ihaFsUdFPzRX6LqHCQq7VWA+FVQJCsgHxlcU8+ShHcv0jh745ClcMwi4mCZl1fO1L9HupnobVCXodRwaXJ1ZSDGlSG/qr5BevbKn5KRybg7CHBgcIMwhMfkODDB06XXBQ=='
# POST requests use a content type header. For DynamoDB,
# the content is JSON.
content_type = 'application/json'
# DynamoDB requires an x-amz-target header that has this format:
# DynamoDB_<API version>.<operationName>
#amz_target = 'DynamoDB_20120810.CreateTable' # Request parameters for CreateTable--passed in a JSON block.
request_parameters = '{'
request_parameters += '"password": ":1:1525246193:5aR5eYKn6zsQ6vIp"'
request_parameters += '}' # Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() 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 # Read AWS access key from env. variables or configuration file. Best practice is NOT
# to embed credentials in code.
access_key = "ASIAJCV4GTJQPYRAYKYQ"
secret_key = "JJ+BouOzY53lEkJMuQ/w/PtWQaCgo32sEwzD4mw+"
if access_key is None or secret_key is None:
print 'No access key is available.'
sys.exit() # Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
date_stamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope amz_date = "20180502T073321Z"
date_stamp = "" # ************* TASK 1: CREATE A CANONICAL REQUEST *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html # Step 1 is to define the verb (GET, POST, etc.)--already done. # Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
canonical_uri = '/dev/v1/user/associations/robots/3147C60040239620' ## Step 3: Create the canonical query string. In this example, request
# parameters are passed in the body of the request and the query string
# is blank.
canonical_querystring = '' # Step 4: Create the canonical headers. Header names must be trimmed
# and lowercase, and sorted in code point order from low to high.
# Note that there is a trailing \n.
amz_content_sha256 = hashlib.sha256(request_parameters).hexdigest()
canonical_headers = 'host:' + host + '\n' + 'x-amz-content-sha256:' + amz_content_sha256 + '\n' + 'x-amz-date:' + amz_date + '\n' + 'x-amz-security-token:' + amz_security_token + '\n'
#SignedHeaders=host;x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=3bd5e785b3e5110bb4a53b375013ec6888a8fe51ff3f4fa2b05e17ce4457896b
# Step 5: Create the list of signed headers. This lists the headers
# in the canonical_headers list, delimited with ";" and in alpha order.
# Note: The request can include any headers; canonical_headers and
# signed_headers include those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
# For DynamoDB, content-type and x-amz-target are also required.
signed_headers = 'host;x-amz-content-sha256;x-amz-date;x-amz-security-token' # Step 6: Create payload hash. In this example, the payload (body of
# the request) contains the request parameters.
payload_hash = hashlib.sha256(request_parameters).hexdigest() # Step 7: Combine elements to create canonical request
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash # ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request).hexdigest() # ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
signing_key = getSignatureKey(secret_key, date_stamp, region, service) # Sign the string_to_sign using the signing_key
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest() # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# Put the signature information in a header named Authorization.
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature # For DynamoDB, the request can include any headers, but MUST include "host", "x-amz-date",
# "x-amz-target", "content-type", and "Authorization". Except for the authorization
# header, the headers must be included in the canonical_headers and signed_headers values, as
# noted earlier. Order here is not significant.
# # Python note: The 'host' header is added automatically by the Python 'requests' library.
headers = {'X-Amz-Date':amz_date,
'x-amz-security-token':amz_security_token,
'Content-Type':content_type,
'x-amz-content-sha256':amz_content_sha256,
'Accept': 'application/json; charset=utf-8',
'Authorization':authorization_header,
'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.0; Nexus 9 Build/NRD90M)'} # ************* SEND THE REQUEST *************
print '\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++'
#GET请求需要适当修改加入?和参数
#request_url = endpoint + canonical_uri + '?' + canonical_querystring
print 'Request URL = ' + endpoint + canonical_uri
print headers
r = requests.post(endpoint + canonical_uri, data=request_parameters, headers=headers) print '\nRESPONSE++++++++++++++++++++++++++++++++++++'
print 'Response code: %d\n' % r.status_code
print r.text
Python编写AWS Version 4 signing (AWS4-HMAC-SHA256) for execute-api的更多相关文章
- [译]Python编写虚拟解释器
使用Python编写虚拟机解释器 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou,密码shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环 ...
- 【转】python编写规范——中标软件有限公司测试中心
[转]python编写规范 一.说明 二.内容 1. 代码布局 1.1 缩进 1.2 表达式和语句中的空格 1.3 行的最大长度 1.4 空行... 1.5 编码... 2. 语句... 2.1 标准 ...
- 使用 Python 编写脚本并发布
使用 Python 编写脚本并发布 P1: 脚本 通常在 Linux 服务器上会遇到在命令行中输入命令的操作,而有些操作包含的命令数目较多或者其中的命令包含的参数较多,如果一个一个的敲命令的话就太麻烦 ...
- 使用 Python 编写 vim 插件
使用 Python 编写 vim 插件 - 技术翻译 - 开源中国社区 code {margin: 0;padding: 0;white-space: pre;border: none;backgro ...
- (转)python编写登录接口
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://506554897.blog.51cto.com/2823970/1907262 ...
- 【MonkeyRunner】[技术博客]用python编写脚本查看设备信息
[MonkeyRunner]用python编写脚本查看设备信息 原以为是个简单的操作,在实践的时候发现了一些问题. python脚本 test.py: from com.android.monkeyr ...
- python--基础1(pip,虚拟环境、python编写规范)
python简介 1.Python是一种解释型脚本语言; 2.Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读.易维护,并且被大量用户所欢迎的.用途广泛的语言; 3.pytho ...
- 【Azure 应用服务】App Service中运行Python 编写的 Jobs,怎么来安装Python包 (pymssql)呢?
问题描述 在App Service中运行Python编写的定时任务,需要使用pymssql连接到数据库,但是发现使用 python.exe -m pip install --upgrade -r re ...
- 基于python编写的天气抓取程序
以前一直使用中国天气网的天气预报组件都挺好,可是自从他们升级组件后数据加载变得非常不稳定,因为JS的阻塞常常导致网站打开速度很慢.为了解决这个问题决定现学现用python编写一个抓取程序,每天定时抓取 ...
随机推荐
- Android下载文件提示文件不存在。。。 java.io.FileNotFoundException
遇到这个错误java.io.FileNotFoundException,事实上文件是存在的,把地址复制到手机浏览器都能够直接下载的,但为嘛不能下载呢. Error in downloadBitmap ...
- MySQL经常使用的面试题
1.怎样登陆mysql数据库 MySQL -u username -p 2.怎样开启/关闭mysql服务 service mysql start/stop 3.查看mysql的状态 service m ...
- [GeekBand] C++ 基础知识一 ——通过引用传递数组
本文参考 : C++ Primer (第四版) 7.2.4及 16.1.5 相关章节 GeekBand 侯捷老师,学习笔记 开发环境采用:VS2013版本 关键问题一.传递引用与传指针.传值的区别? ...
- PCI的imagework已由freeview软件代替
作者:朱金灿 来源:http://blog.csdn.net/clever101 在PCI 9.1中重要模块集成显示环境imagework还存在,但是到了PCI 10.0中imagework已经消失了 ...
- zoj 1008 Gnome Tetravex
开放式存储阵列为每平方米有几个,否则,超时-- #include <stdio.h> #include <string.h> #include <iostream> ...
- 浅谈CAS(Compare and Swap) 原理
浅谈CAS原理java并发编程也研究了一段时间了,对CAS的原理总是不太理解,今天再研究了一下,记录一些自己的理解. 说到CAS,再java中的某些情况下,甚至jdk1.5以后的大多数情况,并发 ...
- Ubuntu server使用命令行上板VPNclient
Ubuntu server使用命令行上板VPNclient VPN,虚拟专用网络,这个技术还是非常有用的.近期笔者參与的项目中就使用上了VPN,大概情况是这种.有两个开发团队,在异地,代码服务器在深圳 ...
- iOS6 与iOS7以及7以上状态栏的颜色设置
iOS7默认状态栏文字颜色为黑色 修改为白色的方法:(chenyong注意 我的Status bar style 使用的仍是默认值Gray style(default)) 1在Info.plist中设 ...
- Linq知识小总结
一.投影操作符 Select Select操作符对单个序列或集合中的值进行投影. 返回 IEnumerable<类名> //查询语法 var query = from e in db.Em ...
- 配置文件——App.config文件读取和修改
作为普通的xml文件读取的话,首先就要知道怎么寻找文件的路径.我们知道一般配置文件就在跟可执行exe文件在同一目录下,且仅仅在名称后面添加了一个.config 因此,可以用Application.Ex ...