You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python HMAC-SHA256计算支持批量参数、txt文件输入的实现方案问询

Python HMAC-SHA256 多输入场景实现方案

支持的功能如下:

  • 兼容原有单个raw值计算逻辑
  • 支持raw参数传入字符串列表完成批量计算
  • 支持读取txt文件逐行导入待计算内容批量处理

完整实现代码

import hashlib
import hmac
import base64
from typing import Union, List, Optional

def hmac_sha256_calc(
    key: str = "BF04AA6B-E243-4D35-A32B-AD82B4220905",
    raw_input: Optional[Union[str, List[str]]] = None,
    file_path: Optional[str] = None
) -> dict:
    key_bytes = bytes(key, encoding="ascii")
    input_list = []
    
    # 优先读取txt文件内容
    if file_path:
        try:
            with open(file_path, "r", encoding="ascii") as f:
                for line in f:
                    line_content = line.strip()
                    # 自动跳过空行
                    if line_content:
                        input_list.append(line_content)
        except FileNotFoundError:
            return {"error": f"文件{file_path}不存在"}
    
    # 处理raw参数输入
    elif raw_input:
        if isinstance(raw_input, str):
            input_list = [raw_input]
        elif isinstance(raw_input, list):
            input_list = raw_input
        else:
            return {"error": "raw_input仅支持字符串或字符串列表格式"}
    else:
        return {"error": "请传入raw_input参数或file_path参数"}
    
    # 批量计算哈希值
    result = {}
    for raw in input_list:
        raw_bytes = bytes(raw, encoding="ascii")
        hashed = hmac.new(key_bytes, raw_bytes, hashlib.sha256)
        result[raw] = base64.b64encode(hashed.digest()).decode()
    return result

使用示例

1. 单个raw值计算(兼容原有逻辑)

res = hmac_sha256_calc(raw_input="5207089087__540500390673_")
print(res)

2. 传入字符串列表批量计算

input_list = ["5207089087__540500390673_", "test_val_001", "test_val_002"]
res = hmac_sha256_calc(raw_input=input_list)
print(res)

3. 读取txt文件批量计算

txt文件每行放置一个待计算值,自动过滤空行,示例input.txt内容:

5207089087__540500390673_
test_val_001
test_val_002

调用方法:

res = hmac_sha256_calc(file_path="./input.txt")
print(res)

内容的提问来源于stack exchange,提问作者Manjunath Gowda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 15:15:08