使用SignedXml类添加基于Id属性的引用时,"格式错误的引用元素"

Dog*_*ars 19 c# xml soap cryptography xml-signature

当存在名称空间前缀时,无法通过Id属性对元素进行签名:

void Main()
{
    var doc = new XmlDocument();
    doc.LoadXml("<root xmlns:u=\"myuri\"><test u:Id=\"_0\">Zebra</test></root>");

    SignedXml signedXml = new SignedXml(doc);
    signedXml.SigningKey = new RSACryptoServiceProvider();

    Reference reference = new Reference("#_0");
    signedXml.AddReference(reference);

    signedXml.ComputeSignature();
}
Run Code Online (Sandbox Code Playgroud)

ComputeSignature() 这里会出现'格式错误的参考元素'应该怎么做?

Dog*_*ars 41

我们使用的方法是继承System.Security.Cryptography.Xml.SignedXml类...

public class SignedXmlWithId : SignedXml
{
    public SignedXmlWithId(XmlDocument xml) : base(xml)
    {
    }

    public SignedXmlWithId(XmlElement xmlElement) 
        : base(xmlElement)
    {       
    }

    public override XmlElement GetIdElement(XmlDocument doc, string id)
    {
        // check to see if it's a standard ID reference
        XmlElement idElem = base.GetIdElement(doc, id);

        if (idElem == null)
        {
            XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
            nsManager.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            idElem = doc.SelectSingleNode("//*[@wsu:Id=\"" + id + "\"]", nsManager) as XmlElement;
        }

        return idElem;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我有同样的错误,但问题是 SecurePart\Id 的值以数字开头(只允许使用字符)。 (4认同)
  • @JanFriedrich,这也是我的问题。我正在使用 SAML 请求的 ID。必须符合 XML ID 约定。请参阅 https://www.w3.org/TR/xml-id/,这是一个 NCNAME https://www.w3.org/TR/xml-names11/#NT-NCName,其起始字符受到限制。我使用了不带大括号的 GUID,只是在其前面添加了 _ 作为 ID。 (3认同)
  • 你是我今天的英雄。谢谢。 (2认同)
  • @JanFriedrich你应该发布一个有效的答案,如果正确的话我愿意接受。 (2认同)