在Python中复制/验证SOAP请求中的XMLDSig,可以使用第三方库 xmlsec
来处理XML数字签名(XMLDSig)。
XML数字签名是一种用于验证XML文档的完整性和身份验证的标准。它使用公钥加密和私钥解密的方式来确保数据的安全性。
以下是在Python中复制/验证SOAP请求中的XMLDSig的步骤:
xmlsec
库:在命令行中运行 pip install xmlsec
来安装 xmlsec
库。import xmlsec
from lxml import etree
# 从SOAP请求中提取XMLDSig签名
soap_request = """
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<!-- XMLDSig签名内容 -->
</ds:Signature>
</wsse:Security>
</soap:Header>
<soap:Body>
<!-- SOAP请求体内容 -->
</soap:Body>
</soap:Envelope>
"""
# 解析SOAP请求
soap_tree = etree.fromstring(soap_request)
# 提取XMLDSig签名
signature_node = soap_tree.xpath("//ds:Signature", namespaces={"ds": "http://www.w3.org/2000/09/xmldsig#"})[0]
signature_xml = etree.tostring(signature_node)
# 复制XMLDSig签名
copied_signature = etree.fromstring(signature_xml)
# 从SOAP请求中提取XMLDSig签名和原始XML内容
soap_request = """
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<!-- XMLDSig签名内容 -->
</ds:Signature>
</wsse:Security>
</soap:Header>
<soap:Body>
<!-- SOAP请求体内容 -->
</soap:Body>
</soap:Envelope>
"""
# 解析SOAP请求
soap_tree = etree.fromstring(soap_request)
# 提取XMLDSig签名和原始XML内容
signature_node = soap_tree.xpath("//ds:Signature", namespaces={"ds": "http://www.w3.org/2000/09/xmldsig#"})[0]
signature_xml = etree.tostring(signature_node)
original_xml = etree.tostring(soap_tree, encoding="unicode")
# 验证XMLDSig签名
doc = xmlsec.parseMemory(original_xml, xmlsec.Type.DOCUMENT)
dsig_ctx = xmlsec.DSigCtx()
dsig_ctx.signKey = xmlsec.Key.fromMemory(signature_xml, xmlsec.KeyFormat.XMLSEC_NODE, None)
dsig_ctx.verify(doc)
领取专属 10元无门槛券
手把手带您无忧上云