繁体   English   中英

使用XSD验证签名的XML-XMLDSig

[英]Validate signed XML with XSD - xmldsig

我对XMLDSig有点新。 我的XML需要签名。 在我所在的项目中,我需要在标志之前和标志之后针对XSD验证XML。

我对XSD不太了解,但是我认为这里是另一个XSD的导入。 这就是我的麻烦开始的地方。 我的XSD文件是masive.xsd ,这是开始时的样子。

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    elementFormDefault="qualified">
    <xs:import namespace="http://www.w3.org/2000/09/xmldsig#"
        schemaLocation="xmldsig-core-schema.xsd"/>

在我的代码C#中,我使用了一些在Internet上找到的代码,这些代码可以正常工作,因为当我尝试针对XSD验证XML时,它会显示发现的错误。 但是,当我尝试验证签名的XML时,我的麻烦就开始了。

如果我按原样使用该类,则无需进行任何更改。 当我使用函数pathSchema添加架构时:

SchemaSet.Add(null, pathSchema);  //pathSchema is the path where my xsd file is.

我收到此错误:

The 'http://www.w3.org/2000/09/xmldsig#:Signature' element is not declared.

如果我是对的,这是因为签名的XML具有如下标记:

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="xmldsig-aae8151c-b8db-4525-bfb1-0b3cebdd1dbf">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
<ds:Reference URI="#xmldsig-aae8151c-b8db-4525-bfb1-0b3cebdd1dbf-keyinfo">
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<ds:DigestValue>p4U9Np1nKtjWPPwp2mOcIimRjUy+RuQIPr2hVdY5R2E=</ds:DigestValue>
</ds:Reference>

我读过一些文章,在其中一篇文章中,我读到有人认为我手动添加了XSD。 因此,我下载了XSD并放入了本地路径,然后将其添加到代码中:

    XElement xsdMarkup2 = XElement.Load(@"C:\XMLXSD\xmldsig-core-schema.xsd");
    settings.Schemas.Add(null, xsdMarkup2.CreateReader());

并且不会显示错误“未声明签名元素”。 但是,验证器不再验证签名的XML。 因为我已经删除了一些标签,并且该类说:没有错误。 但是有。

好的,我终于设法解决了。

我使用了此解决方案,这是各种解决方案的混合。 我下载了xmldsig-core-schema.xsd并进行了编辑,因为它包含一些带有注释的行,当我尝试验证xml时会抛出异常,指出xsd模式中的第一行必须类似于

<schema xmlns="http://www.w3.org/2001/XMLSchema"

好吧,这是C#代码的一部分

                XmlSchemaSet ss = new XmlSchemaSet();
                ss.Add(null, @"C:\Masive.xsd");

                XmlReaderSettings settings2 = new XmlReaderSettings();
                settings2.DtdProcessing = DtdProcessing.Parse;

                XmlReader reader = XmlReader.Create(@"C:\xmldsig-core-schema.xsd", settings2);

                ss.Add(null, reader);
                ss.Compile();

我敢肯定这不是最好的方法(我想),但是它对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM