我对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进行了签名,从这里开始,我将尝试了解在何处或如何生成这些值。我正在跟踪这的上下文。我能够验证DigestValue,现在我正在尝试获取SignatureValue。从堆栈溢出中的链接和其他一些问题来看,我只需要:
SignedInfo元素才能得到签名值。我正在使用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>我正在使用密码学来尝试生成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。我怎样才能做到这一点?
发布于 2019-10-30 12:15:01
你的问题是你做了两次哈希。sign()函数为您执行散列操作,这样您就可以跳过中间部分。
只需使用规范化的sign()元素调用SignedInfo:
signature_1v15 = private_key.sign(
sign_info,
padding.PKCS1v15(),
hashes.SHA256()
)https://stackoverflow.com/questions/57902442
复制相似问题