如何在 C# 中向签名元素添加前缀

本文关键字:元素 添加 加前缀 | 更新日期: 2023-09-27 18:36:59

我们使用 SignedXml 类对 xml 元素进行签名。要求在 Ws Security 中添加签名节点以与服务通信。

我们可以签署这些元素并验证这些元素。在本例中,xml 示例代码如下所示

        X509Certificate2 certificate = new X509Certificate2(CertPath, CertPassword);
    // Create a new XML document.
    XmlDocument doc = new XmlDocument();
    // Format the document to ignore white spaces.
    doc.PreserveWhitespace = false;
    // Load the passed XML file using it's name.
    doc.Load(new XmlTextReader(FileName));
    SignedXml signedXml = new SignedXml(doc);
    signedXml.SigningKey = certificate.PrivateKey;

    // Create a reference to be signed.
    Reference reference = new Reference();
    reference.Uri = "#" + elementID;
    // Add an enveloped transformation to the reference.
     XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(envTransform);
    // Add the reference to the SignedXml object.
    signedXml.AddReference(reference);

    // Create a new KeyInfo object.
    KeyInfo keyInfo = new KeyInfo();
    // Load the certificate into a KeyInfoX509Data object
    // and add it to the KeyInfo object.
    keyInfo.AddClause(new KeyInfoX509Data(certificate));
    // Add the KeyInfo object to the SignedXml object.
    signedXml.KeyInfo = keyInfo;
    // Compute the signature.
    signedXml.ComputeSignature();

    // Get the XML representation of the signature and save
    // it to an XmlElement object.
    XmlElement xmlDigitalSignature = signedXml.GetXml();

通过使用生成为<signature> .... </signature>的签名元素,但我们希望将其生成为><ds:signature> .... </ds:signature>>

已尝试显式设置前缀,但之后未验证签名。

您能否指导我们如何实现这一目标?

如何在 C# 中向签名元素添加前缀

由于这是一个足够通用的问题,这篇文章可能对寻找相同信息的人有所帮助。

对于我正在从事的特定项目,IRS A2A 提交,这是我在考虑需要将前缀添加到Signature元素时使用的。 但是,在与其他一些SO用户的讨论中,我已经放弃了将前缀添加到Signature元素的想法,因为这实际上不是必需的。