当前位置: 首页 > article >正文

AWS 签名算法SigV4 的python实现

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

#!/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)


http://www.kler.cn/a/516987.html

相关文章:

  • Scade 表达式 - 使用索引的迭代器
  • 9、Docker环境安装Nginx
  • windows平台通过命令行安装前端开发环境
  • nginx分发请求超时切换服务
  • redis离线安装部署详解(包括一键启动)
  • 简识JVM栈帧中的操作数栈
  • Oracle Agile PLM Web Service Java示例测试开发(一)环境环境、准备说明
  • easyexcel读取写入excel easyexceldemo
  • 梯度下降法 (Gradient Descent) 算法详解及案例分析
  • 3、C#基于.net framework的应用开发实战编程 - 实现(三、二) - 编程手把手系列文章...
  • 如何高效、优雅地利用正则表达式
  • EtherCAT介绍和总线结构
  • 一文了解二叉树的遍历和线索二叉树
  • 微服务学习-SkyWalking 实时追踪服务链路
  • CTFSHOW-WEB入门-文件包含78-81
  • Spring WebFlux 和 Spring MVC 的主要区别是什么?
  • springboot使用ssl连接elasticsearch
  • 【开源免费】基于SpringBoot+Vue.JS校园失物招领系统(JAVA毕业设计)
  • FastExcel导入Excel详细步骤
  • MyBatis-Plus之常用注解
  • Java定时任务实现方案(二)——ScheduledExecutorService
  • C#通过SDK包与三菱PLC仿真通讯
  • Java数据结构方面的面试试题以及答案解析
  • 【Go面试】基础八股文篇 (持续整合)
  • 加州大学伯克利分校最新研究:通过语言融合视听触觉异构传感器实现机器人通用操作策略微调
  • Python识别处理验证码技术详解