Python xmlsec XML签名值不匹配

问题描述 投票:0回答:1

我是xml签名的新手,目前正在使用xmlsec生成签名的xml。我对示例代码进行了一些修改:

from lxml import etree
import xmlsec

parser = etree.XMLParser(remove_blank_text=True)
template = etree.parse('unsigned.xml', parser).getroot()

signature_node = xmlsec.tree.find_node(template, xmlsec.constants.NodeSignature)
ctx = xmlsec.SignatureContext()
key = xmlsec.Key.from_file('keys/private_key.pem', xmlsec.constants.KeyDataFormatPem)
ctx.key = key
sig_ = ctx.sign(signature_node)
formated = etree.tostring(template)
with open('signed_test.xml', 'wb') as the_file:
    the_file.write(formated)

现在我已经签署了XML,从这里我试图了解在何处或如何生成值。我关注的是this。我能够验证DigestValue,现在我正在尝试获取SignatureValue。从stackoverflow中的链接和其他一些问题,我只需要:

  1. 将整个SignedInfo元素规范化
  2. 哈希结果
  3. 签名哈希

为了获得签名值。我正在使用SignedInfo规范化lxml元素:

from lxml import etree

parser = etree.XMLParser(remove_blank_text=True)
xmlTree = etree.parse('signed_info.xml', parser)
root = xmlTree.getroot()
formated = etree.tostring(root, method='c14n', exclusive=True)
# Write to file
with open('canon_sinfo.xml', 'wb') as the_file:
    the_file.write(formated)

有关信息,以下是所得的SignedInfo

<SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></CanonicalizationMethod><SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></SignatureMethod><Reference URI="#obj"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#base64"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></DigestMethod><DigestValue>izbIdQ4tSAg6VKGpr1zd6kU9QpVQi/Bcwxjxu/k2oKk=</DigestValue></Reference></SignedInfo>

我正在使用cryptography尝试生成SignatureValue,但是我无法获得与生成的xmlsec相同的结果。

这是我的代码段:

sign_info = '''String of the Sign Info'''
digest_sinfo = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest_sinfo.update(bytes(sign_info, 'utf-8'))
digested_sinfo = digest_sinfo.finalize()

# Load private_key here...

# Sign the message
signature_1v15 = private_key.sign(
    digested_sinfo,
    padding.PKCS1v15(),
    hashes.SHA256()
)

我还尝试将SignedInfo加载到单独的文件中,但是我仍然得到不匹配的SignatureValue。我该如何完成?

python-3.x lxml xml-signature python-cryptography
1个回答
0
投票

您的问题是您进行了两次哈希处理。 sign()函数为您执行哈希处理,因此您可以跳过中间部分。

只需使用您的规范化SignedInfo元素调用sign()

signature_1v15 = private_key.sign(
    sign_info,
    padding.PKCS1v15(),
    hashes.SHA256()
)
© www.soinside.com 2019 - 2024. All rights reserved.