PyHanko PDF CMS签名验证遇政策限制错误,求自定义配置方案
PyHanko PDF CMS签名验证问题及解决方案
问题概述
- CLI验证报错:
- 错误1:
ERROR - An error occurred while validating this signature: The algorithm sha256_rsa is not allowed by the current usage policy. Reason: Key size 1024 for algorithm rsassa_pkcs1v15 is considered too small; policy mandates >= 2048. [AdESIndeterminate.CRYPTO_CONSTRAINTS_FAILURE] - 错误2:
An error occurred while validating this signature: The algorithm sha1 is not allowed by the current usage policy. [AdESIndeterminate.CRYPTO_CONSTRAINTS_FAILURE] Error: Validation failed
- 错误1:
- 代码验证额外问题:除上述SHA1算法错误外,还触发
/Type异常 - 对比情况:终端工具
pdfsig可正常返回所有签名数据,此前尝试过endesive库
PyHanko自定义验证策略配置步骤
1. 调整加密约束规则
PyHanko默认加密策略要求RSA密钥至少2048位,且禁用SHA1算法。要放宽这些限制,需自定义CryptoPolicy并绑定到验证上下文:
from pyhanko.sign.validation.policy import CryptoPolicy, ValidationContext from pyhanko.sign.general import validate_pdf_signature from pyhanko.pdf_utils.reader import PdfFileReader # 自定义加密策略,允许1024位RSA密钥和SHA1算法 custom_crypto_policy = CryptoPolicy( min_rsa_key_size=1024, allow_sha1=True ) # 构建带自定义策略的验证上下文,同时关闭严格语法检查解决/Type异常 validation_ctx = ValidationContext( crypto_policy=custom_crypto_policy, strict_syntax=False ) # 执行签名验证 with open('download.pdf', 'rb') as f: pdf_file = PdfFileReader(f) for sig in pdf_file.embedded_signatures: print("*" * 10, sig, "*" * 10) try: status = validate_pdf_signature(sig, context=validation_ctx) print(status.pretty_print_details()) except Exception as e: print(e)
2. CLI模式下应用自定义策略
创建TOML配置文件(例如custom_policy.toml):
[validation.crypto] min-rsa-key-size = 1024 allow-sha1 = true [validation] strict-syntax = false
执行验证命令时指定配置文件:
python -m pyhanko sign validate --config custom_policy.toml --pretty-print --no-diff-analysis download.pdf
替代工具:endesive配置示例
如果使用endesive,可通过以下方式放宽验证规则:
from endesive import pdf def validate_pdf(pdf_path): with open(pdf_path, 'rb') as f: pdf_data = f.read() # 关闭严格模式,允许SHA1算法 verify_results = pdf.verify(pdf_data, strict=False, allow_sha1=True) for idx, result in enumerate(verify_results): print(f"签名{idx+1}验证结果:") print(f"有效性: {result[0]}, 说明: {result[1]}, 签名者信息: {result[2]}") validate_pdf('download.pdf')
内容的提问来源于stack exchange,提问作者ErfanDyaco
相关产品推荐
相关产品推荐

