首页 > 解决方案 > Python signxml XML 签名包。如何为 Signature 标签添加 xml 占位符?

问题描述

我是 Python 新手。我已经安装了 signxml 包,我正在做 xml 签名过程。

链接到 python 包:https ://pypi.org/project/signxml/

我的 xml 文件正在生成。但是 XML 签名代码几乎没有什么不同。我能够匹配大部分部分,但我不知道如何匹配以下部分。

任何人都可以帮助我。

不同的部分是以下标签

<Signature>

以上部分应该是这样的

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">

在此处输入图像描述

当我搜索 signxml 核心文件时,我发现了以下注释。

To specify the location of an enveloped signature within **data**, insert a
``<ds:Signature Id="placeholder"></ds:Signature>`` element in **data** (where
"ds" is the "http://www.w3.org/2000/09/xmldsig#" namespace). This element will
be replaced by the generated signature, and excised when generating the digest.

如何做出改变来改变它。以下是我的python代码

from lxml import etree
import xml.etree.ElementTree as ET
from signxml import XMLSigner, XMLVerifier
import signxml

el = ET.parse('example.xml')
root = el.getroot()

#cert = open("key/public.pem").read()
key = open("key/private.pem").read()

signed_root = XMLSigner(method=signxml.methods.enveloped,signature_algorithm='rsa-sha512',digest_algorithm="sha512").sign(root, key=key)

tree = ET.ElementTree(signed_root)


#dv = tree.findall(".//DigestValue");
#print(dv);

tree.write("new_signed_file.xml")

上面的代码在做什么。它需要一个xml文件并进行数字签名处理并生成新文件。

任何人都可以指导我在哪里以及我应该为这个要求做些什么改变?

标签: pythonxmlxml-signature

解决方案


我假设您正在使用 python signxml

转到 python 设置并打开此文件Python\Lib\site-packages\signxml\ __init__.py

打开__init__.py文件并进行以下更改。

找到以下代码

def _unpack(self, data, reference_uris):
        sig_root = Element(ds_tag("Signature"), nsmap=self.namespaces)

使用以下代码进行更改。

def _unpack(self, data, reference_uris):
        #sig_root = Element(ds_tag("Signature"), nsmap=self.namespaces)
        sig_root = Element(ds_tag("Signature"), xmlns="http://www.w3.org/2000/09/xmldsig#")

完成此更改后,重新编译您的 python signxml package

重新生成新的 xml 签名文件。


推荐阅读