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

使用XML与PEM文件验证签名时加载密钥报错求助

XML签名验证中加载PEM证书失败的解决指引

问题场景

我有一个包含证书的test.pem文件和一份带签名信息的test.xml文件,使用以下Python代码进行签名验证:

# Parse the XML document
template = etree.parse("test.xml").getroot()
print("Template", template.tag)

# Add ID attributes
xmlsec.tree.add_ids(template, ["ID"])

# Print the loaded XML template
print(etree.tostring(template, pretty_print=True).decode())

# Find the signature node
signature_node = xmlsec.tree.find_node(template, xmlsec.constants.NodeSignature)

# Print the signature node
if signature_node is not None:
    print(etree.tostring(signature_node, pretty_print=True).decode())
else:
    print("Signature node not found")
    exit(1)

# Create a digital signature context (no key manager is needed).
ctx = xmlsec.SignatureContext()
print("Digital Signature", ctx)

# Load the key from file
try:
    key = xmlsec.Key.from_file(
        "test.pem",
        xmlsec.constants.KeyDataFormatPem,
    )
    print("Key loaded successfully.")
except Exception as e:
    print(f"Error loading key: {e}")
    exit(1)

# Set the key on the context.
ctx.key = key

# Verify the signature
try:
    ctx.verify(signature_node)
    print("Validated")
except xmlsec.VerificationError as e:
    print(f"Not Verified: {e}")
except Exception as e:
    print(f"Error: {e}")

错误信息

运行代码时出现以下错误:

Error loading key: (1, 'cannot read key')

错误发生在加载密钥的代码行:

key = xmlsec.Key.from_file(
    "test.pem",
    xmlsec.constants.KeyDataFormatPem,
)

排查与解决步骤

  • 检查文件路径与权限
    确认test.pem文件路径正确,代码运行时能访问到该文件。相对路径需确保文件在当前工作目录,绝对路径要检查拼写。同时给文件添加可读权限:Linux/macOS下执行chmod 644 test.pem,Windows下右键设置文件权限为可读。
  • 验证PEM文件格式
    打开test.pem确认格式有效性:证书文件开头应为-----BEGIN CERTIFICATE-----,结尾为-----END CERTIFICATE-----;如果是私钥则对应-----BEGIN PRIVATE KEY-----或算法专属头(如RSA私钥)。签名验证通常需要公钥或证书,确认文件类型与需求匹配。
  • 从证书提取公钥
    若test.pem是完整证书,xmlsec可能无法直接加载,可先用openssl提取公钥:
    openssl x509 -in test.pem -pubkey -noout > public_key.pem
    
    修改代码中文件路径为public_key.pem后重试。
  • 指定密钥类型
    加载密钥时显式指定密钥类型,比如RSA公钥:
    key = xmlsec.Key.from_file(
        "test.pem",
        xmlsec.constants.KeyDataFormatPem,
        xmlsec.constants.KeyDataTypePublicKey
    )
    
  • 检查xmlsec依赖
    确认系统已安装底层依赖库:Ubuntu/Debian安装libxmlsec1-dev和libxmlsec1-openssl;macOS用Homebrew安装xmlsec1;Windows可通过Chocolatey或手动安装xmlsec1二进制包。

内容的提问来源于stack exchange,提问作者Kajol Mehta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:48:29