AWS 签名算法SigV4 的python实现

最近测试bedrock API。用它验证签名。

python 复制代码
#!/usr/bin/env python
# coding=utf-8

import hashlib
import hmac

# 定义函数:生成 SHA256 哈希
def sha256_hash(data):
    return hashlib.sha256(data.encode('utf-8')).hexdigest()

# 定义函数:HMAC-SHA256 签名
def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

# 定义函数:生成签名密钥
def get_signature_key(secret_key, date_stamp, region_name, service_name):
    k_date = sign(('AWS4' + secret_key).encode('utf-8'), date_stamp)
    k_region = sign(k_date, region_name)
    k_service = sign(k_region, service_name)
    k_signing = sign(k_service, 'aws4_request')
    return k_signing

# 1. 规范请求
http_method = "POST"
canonical_uri = "/model/us.anthropic.claude-3-5-sonnet-20241022-v2%3A0/converse"
canonical_querystring = ""  # 空查询字符串
payload_hash = sha256_hash("{\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"Provide general steps to debug a BSOD on a Windows laptop.\"}]}],\"system\":[{\"text\":\"You are a tech support expert who helps resolve technical issues. Signal SUCCESS if you can resolve the issue, otherwise FAILURE\"}],\"inferenceConfig\":{\"stopSequences\":[\"SUCCESS\",\"FAILURE\"]},\"additionalModelRequestFields\":{\"top_k\":200}}")  # 空 JSON 请求体的哈希值
print("payload_hash:\n"+payload_hash)

canonical_headers = (
    "host:bedrock-runtime.us-east-1.amazonaws.com\n"
    "x-amz-date:20250122T092741Z\n"
    "x-amz-security-token:IQoJb3JpZ2luX2VjENL//wEaCXVzLWVhc3QtMSJHMEUCIFUZwfu0CLXeFAD0WEWchvmxEx+iVxRNL1Q17ti0SwwcAiEAoOeBi0ocqsTkQNFcpYaer3e/B0l3agWrUFlBjw262NcqkgMIy///ARAAGgwwMDM4MzM5ODk3NDQiDECroDnHWInBWYPNdyrmAsgweKDdPZPmU507A9prUbnTW5aE7HeS3BXFbXODqMCmtv1EVDINli1DuIYfY08rVyne50o9AtpqMgJd27mE9QCS9cfDsCAH+KQfBiyVmoDPiSGiEBhnt/GB/t8lg3uOug8AyF+/+YEi12xNkHfhF3sM5y1HdVllXp1VjHpBq1UIZsMh2/kuFnQ+8L9ylO1pUeK5LA+XqfBEwRUrq4LrThS6uPoxOzj5BuMOzWIFRxVdbGYCAgOIv5iVz9I1on30i6ezNlXspc6UcbSY/+rTi72WvDt9nc6wYRVNFy+dNM8QdZv/UkU9IrRerXzyIibSmHSJbgeSfw2iX7ATD6A8aWBzYmSzuj+oh2ztK/8yZq6iCQVkNvxsV6aWQFZJOC6nyV3aKGyDdt8RT8pjBk6n0YBfRs/eWx3gvr4gUhdkJUyLntn5O53ri9RRrQx1YS18rN4w/U6MvSDwKJAu20kSJYAO8o2neAowhZTBvAY6pwHq3PbSD19+Z109czCYImCN4AbvuZv7F55ISFaHJz2L4Q6OuoBM2Wi+MSjuHE9bw2Jz+xRfBsrRwAhru/gjwWTp0yqrQrlOCCn47I/cQwnKYoaGi1m9BRIDJiKz0d7mieBIovHrn7ajB6yKbRWdyWYflj2oARC7Qz3m6zEuT04GEKewQWADoZ1B0YPIxMdeljvgcMJJpqaR0kuqeUi5UcQmvIW2FLenLQ==\n"
)

signed_headers = "host;x-amz-date;x-amz-security-token"

canonical_request = (
    f"{http_method}\n"
    f"{canonical_uri}\n"
    f"{canonical_querystring}\n"
    f"{canonical_headers}\n"
    f"{signed_headers}\n"
    f"{payload_hash}"
)
hashed_canonical_request = sha256_hash(canonical_request)

# 2. 待签名字符串
algorithm = "AWS4-HMAC-SHA256"
timestamp = "20250122T092741Z"
date_stamp = "20250122"
region_name = "us-east-1"
service_name = "bedrock"

credential_scope = f"{date_stamp}/{region_name}/{service_name}/aws4_request"
string_to_sign = (
    f"{algorithm}\n"
    f"{timestamp}\n"
    f"{credential_scope}\n"
    f"{hashed_canonical_request}"
)

# 3. 生成签名密钥
secret_key = "7/LH0q2Oxo5H1wqg4y5hZZVxkJRI19wosNcrItYD"  # 替换为你的 AWS Secret Access Key
signing_key = get_signature_key(secret_key, date_stamp, region_name, service_name)

# 4. 生成最终签名
signature = hmac.new(signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()

# 输出结果
print("Canonical Request:\n"+canonical_request)
print("Hashed Canonical Request:\n"+hashed_canonical_request)
print("String to Sign:\n"+string_to_sign)
print("Signature:\n"+signature)
相关推荐
佛州小李哥1 天前
在亚马逊云科技上用AI提示词优化功能写出漂亮提示词(下)
人工智能·科技·ai·语言模型·云计算·aws·亚马逊云科技
佛州小李哥2 天前
在亚马逊云科技上高效蒸馏低成本、高精度的Llama 3.1 405B模型(上篇)
人工智能·科技·ai·语言模型·云计算·aws·亚马逊云科技
Norris Huang3 天前
Amazon MSK 开启 Public 访问 SASL 配置的方法
kafka·aws
sealaugh324 天前
aws(学习笔记第二十五课) 使用aws batch
笔记·学习·aws
佛州小李哥5 天前
如何在亚马逊云科技上大幅降低无服务器网页应用冷启动时间(上篇)
java·科技·云原生·serverless·开发·aws·亚马逊云科技
HaoHao_0105 天前
AWS Lambda
服务器·网络·云计算·aws·云服务器
还是转转5 天前
关于AWS网络架构的思考
aws
monkey225 天前
AWS S3 跨账户访问 Cross Account Access
云计算·aws
佛州小李哥5 天前
如何在亚马逊云科技上消除无服务器网页应用冷启动时间(下篇)
科技·云原生·serverless·云计算·开发·aws·亚马逊云科技