如何在C#中为Signature元素添加前缀

时间:2016-03-02 12:45:40

标签: c# ws-security x509certificate2 xml-signature signedxml

我们正在使用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();

使用生成为&lt; signature> .... </signature>的此Signature元素。但我们希望将其生成为&lt; ds:signature> .... </ds:signature>

尝试明确设置前缀,但之后不验证签名。

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

1 个答案:

答案 0 :(得分:0)

因为这是一个足够通用的问题,this post might be helpful to someone looking for the same information

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