[英]Malformed reference element signing a xml file of bills
我正在開發一個程序來對 xml 中的發票進行數字簽名。 我遵循了本指南https://www.profissionaisti.com.br/2010/07/assinando-digitalmente-um-xml-usando-c/#comment-197297 。 但是,我收到錯誤格式錯誤的參考元素。 代碼是:
static void Main(string[] args)
{
//open certificates of current user
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
//Open screen to choose certificate
var selectedCertificate = X509Certificate2UI.SelectFromCollection(
store.Certificates,
"Title",
"MSG",
X509SelectionFlag.SingleSelection);
//Gets the x509 object of the selected certificate
foreach (X509Certificate2 x509 in selectedCertificate)
{
try
{
//==============================
// Start reading xml files
//==============================
var txtFiles = Directory.EnumerateFiles("./", "*.xml");
foreach (string currentFile in txtFiles)
{
Console.WriteLine("Reading file " + currentFile + ":");
var originalDoc = XDocument.Load(currentFile);
XmlDocument doc = DocumentExtensions.ToXmlDocument(originalDoc);
//==============================
// Start reading bills
//==============================
獲取xml節點InfRps,它是xml中賬單的表示:
XmlNodeList ListInfRps = doc.GetElementsByTagName("InfRps");
int NodeCounter = 1;
foreach (XmlElement InfRps in ListInfRps)
{
.NET 框架的命名空間 System.Security.Cryptography.Xml 上有一個名為 SignedXml 的類,它實現了 W3C 標准,用於文檔簽名和簽名文檔的驗證。 下面的代碼啟動這個類。
string id = InfRps.Attributes.GetNamedItem("Id").Value;
SignedXml signedXml = new SignedXml(InfRps);
signedXml.SigningKey = x509.PrivateKey;
根據美國國稅局的規定,XML 在處理之前必須以規范的形式存在。 類 Reference 負責處理這部分過程,包括節點 infNFE 的識別和所需的轉換:
// Transformation for DigestValue
Reference reference = new Reference("#" + id);
//Reference reference = new Reference("#" + "lote");
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigC14NTransform());
signedXml.AddReference(reference);
在計算簽名之前,我們必須配置對使用的數字證書信息的處理。 根據這些數據,IRS 能夠驗證簽名,並確保在賬單發送者簽署后沒有修改任何信息。 我們必須包含一個包含證書數據的條款。
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(x509));
signedXml.KeyInfo = keyInfo;
現在,我們應該計算簽名: 這是錯誤。
signedXml.ComputeSignature();
如果計算簽名有效,那么我們可以在 xml 上創建元素簽名:
XmlElement xmlSignature = doc.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");
XmlAttribute attr = doc.CreateAttribute("Id");
attr.Value = "Ass_" + id;
//Add the attribute to the node
xmlSignature.Attributes.SetNamedItem(attr);
XmlElement xmlSignedInfo = signedXml.SignedInfo.GetXml();
XmlElement xmlKeyInfo = signedXml.KeyInfo.GetXml();
XmlElement xmlSignatureValue = doc.CreateElement("SignatureValue", xmlSignature.NamespaceURI);
string signBase64 = Convert.ToBase64String(signedXml.Signature.SignatureValue);
XmlText text = doc.CreateTextNode(signBase64);
xmlSignatureValue.AppendChild(text);
xmlSignature.AppendChild(doc.ImportNode(xmlSignedInfo, true));
xmlSignature.AppendChild(xmlSignatureValue);
xmlSignature.AppendChild(doc.ImportNode(xmlKeyInfo, true));
XmlNodeList ListRps = doc.GetElementsByTagName("Rps");
int RpsCounter = 1;
foreach (XmlElement Rps in ListRps)
{
if (RpsCounter == NodeCounter)
{
Rps.AppendChild(xmlSignature);
}
RpsCounter++;
}
Console.WriteLine("Ok");
NodeCounter++;
}
(...)
我得到 CryptographicException: Malformed reference element:
System.Security.Cryptography.CryptographicException: Malformed reference element.
at System.Security.Cryptography.Xml.Reference.CalculateHashValue(XmlDocument
document, CanonicalXmlNodeList refList)
at System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences()
at System.Security.Cryptography.Xml.SignedXml.ComputeSignature()
at escolhercertificadosimples.Program.Main(String[] args) in
C:\Users\user\Do
cuments\Visual Studio
2015\Projects\assinaturalote\assinaturalote\Program.cs:line 143
Pressione qualquer tecla para continuar. . .
要簽名的 xml 示例如下:
<?xml version="1.0" encoding="UTF-8"?>
<EnviarLoteRpsEnvio xmlns="http://www.abrasf.org.br/nfse.xsd">
<LoteRps Id="lote" versao="1.00">
<NumeroLote>8</NumeroLote>
<Cnpj>09419261123115</Cnpj>
<InscricaoMunicipal>51624621</InscricaoMunicipal>
<QuantidadeRps>1</QuantidadeRps>
<ListaRps>
<Rps xmlns="http://www.abrasf.org.br/nfse.xsd">
<InfRps Id="rps:8201603150148">
<IdentificacaoRps>
<Numero>8201613150148</Numero>
<Serie>248</Serie>
<Tipo>2</Tipo>
</IdentificacaoRps>
<DataEmissao>2016-03-15T18:18:39</DataEmissao>
<NaturezaOperacao>1</NaturezaOperacao>
<OptanteSimplesNacional>2</OptanteSimplesNacional>
<IncentivadorCultural>2</IncentivadorCultural>
<Status>1</Status>
<Servico>
<Valores>
<ValorServicos>20.00</ValorServicos>
<ValorDeducoes>0.00</ValorDeducoes>
<ValorPis>1.60</ValorPis>
<ValorCofins>2.00</ValorCofins>
<ValorInss>0.00</ValorInss>
<ValorIr>3.00</ValorIr>
<ValorCsll>2.00</ValorCsll>
<IssRetido>1</IssRetido>
<OutrasRetencoes>0.00</OutrasRetencoes>
<DescontoIncondicionado>0.00</DescontoIncondicionado>
<DescontoCondicionado>0.00</DescontoCondicionado>
</Valores>
<ItemListaServico>1.07</ItemListaServico>
<CodigoTributacaoMunicipio>10700100</CodigoTributacaoMunicipio>
<Discriminacao>test.</Discriminacao>
<CodigoMunicipio>4314902</CodigoMunicipio>
</Servico>
<Prestador>
<Cnpj>09419261000115</Cnpj>
<InscricaoMunicipal>51624621</InscricaoMunicipal>
</Prestador>
<Tomador>
<IdentificacaoTomador>
<CpfCnpj>
<Cnpj>14525684000150</Cnpj>
</CpfCnpj>
</IdentificacaoTomador>
<RazaoSocial>test S.A.</RazaoSocial>
<Endereco>
<Endereco>Rua test</Endereco>
<Numero>83</Numero>
<Complemento>Sala test</Complemento>
<Bairro>Centro</Bairro>
<CodigoMunicipio>3304557</CodigoMunicipio>
<Uf>RJ</Uf>
<Cep>20091007</Cep>
</Endereco>
<Contato>
<Telefone>2136261100</Telefone>
<Email>test@test.com.br</Email>
</Contato>
</Tomador>
</InfRps>
</Rps>
</ListaRps>
</LoteRps>
</EnviarLoteRpsEnvio>
有人有什么想法嗎? 任何想法都會受到贊賞
您的 Id 值 ( rps:8201603150148
) 中有一個冒號,這對於標識符屬性是非法的。 (根據https://www.w3.org/TR/xml-id/#processing , The normalized value of the attribute is an NCName...
,其中“NCName”的“NC”部分是“no-colon” )
由於 Id 值中的冒號 SignedXml 無法解析它,因此它表示您的參考指向無處。
如果您正在編寫新代碼並且對您的(技術上格式錯誤的)標識符屬性值沒有要求,最好的答案是去掉冒號(下划線通常可以很好地用於此角色)。
由於符合 xml:id 約束可生成最具互操作性的文檔,因此這絕對是最佳答案。
下一個最佳答案是擴展 SignedXml 類並覆蓋GetIdElement
。 你應該讓你的匹配邏輯盡可能嚴格。 請注意,此邏輯必須對簽名者和接收者都執行...並且僅當雙方都能夠接受松散的一致性文檔時才有效。
internal class RpsSignedXml : SignedXml
{
// ctors and other members as appropriate
public override XmlElement GetIdElement(XmlDocument document, string idValue)
{
if (document == null)
return null;
if (string.IsNullOrEmpty(idValue))
return null;
if (!idValue.StartsWith("rps:"))
return base.GetIdElement(document, idValue);
string xPath = $"//InfRps[@Id=\"{idValue}\"]";
XmlNodeList nodeList = document.SelectNodes(xPath);
if (nodeList == null || nodeList.Count != 1)
return null;
return nodeList[0] as XmlElement;
}
}
我有一個類似的問題。 我得到這個例外:
Unable to resolve Uri cid:Part-0986dfc9-2748-41a4-8624-e505e98b29be.
System.Security
at System.Security.Cryptography.Xml.Reference.CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList)
at System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences()
at System.Security.Cryptography.Xml.SignedXml.ComputeSignature()
at EmpTestWeb.BL.ebXMLSigner.ComputeSig(X509Certificate2 cert, XmlDocument doc, String externalReferenceUri) in C:\Websites\TestWeb\BL\ebXMLSigner.cs:line 67
at ASP.ebxml_aspx.GenerateHeaderXML() in c:\Websites\TestWeb\ebXML.aspx:line 227
at ASP.ebxml_aspx.btnSubmit_Click(Object sender, EventArgs e) in c:\Websites\TestWeb\ebXML.aspx:line 89
如果我嘗試使用這個類,它沒有幫助:
class ebXMLSignedXml : SignedXml
{
// ctors and other members as appropriate
public ebXMLSignedXml(XmlDocument doc) : base(doc) { }
public override XmlElement GetIdElement(XmlDocument document, string idValue)
{
if (document == null)
return null;
if (string.IsNullOrEmpty(idValue))
return null;
if (!idValue.StartsWith("cid:"))
return base.GetIdElement(document, idValue);
string xPath = $"//InfRps[@Id=\"{idValue}\"]";
XmlNodeList nodeList = document.SelectNodes(xPath);
if (nodeList == null || nodeList.Count != 1)
return null;
return nodeList[0] as XmlElement;
}
}
它永遠不會到達它應該選擇帶有Id="cid:...."
的元素的位置
解決方案
我最終傳遞了一個內容流而不是 URI,並手動將 URI="cpa:13131312" 屬性添加到生成的 XML 中。
就我而言,在被困幾天之后。 它是 Reference.uri。 我將它保存為“#1”並且它不能以數字開頭,我將它保留在“#test”以及要簽名的 XML 的 ID 中。 我有它“1”,我把它留在“測試”上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.