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
相关产品推荐
相关产品推荐

