使用c#签名xml文档因为特殊字符而不断出现签名验证问题,具体而言,这个“º”通常用于西班牙的地址。
此xml文件的编码是“ISO-8859-1”,但是如果我使用UTF-8,它可以正常工作。
我用于签名的方法就是这个:
public static string SignXml(XmlDocument Document, X509Certificate2 cert)
{
SignedXml signedXml = new SignedXml(Document);
signedXml.SigningKey = cert.PrivateKey;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env =
new XmlDsigEnvelopedSignatureTransform(true);
reference.AddTransform(env);
XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
reference.AddTransform(c14t);
KeyInfo keyInfo = new KeyInfo();
KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
keyInfo.AddClause(keyInfoData);
signedXml.KeyInfo = keyInfo;
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
Document.DocumentElement.AppendChild(
Document.ImportNode(xmlDigitalSignature, true));
return Document.OuterXml;
}
取自:http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html
这就是我所说的:
static void Main(string[] args)
{
string path = ".\\DATOS\\Ejemplo.xml";
string signedDocString = null;
XmlDocument entrada = new XmlDocument();
entrada.Load(path);
X509Certificate2 myCert = null;
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates;
foreach (var certificate in certificates)
{
if (certificate.Subject.Contains("XXXX"))
{
Console.WriteLine(certificate.Subject);
myCert = certificate;
break;
}
}
if (myCert != null)
{
signedDocString = SignXml(entrada, myCert);
}
if (VerifyXml(signedDocString))
{
Console.WriteLine("VALIDO");
}
else
{
Console.WriteLine("NO VALIDO");
}
Console.ReadLine();
}
xml文档必须使用编码ISO-8859-1,这不是可选的。我无法抑制特殊字符。
有关如何处理此事的任何建议吗?
答案 0 :(得分:1)
我的错。
在验证方法中,我使用的是utf8:
public bool VerifyXml( string SignedXmlDocumentString )
{
byte[] stringData = Encoding.UTF8.GetBytes( SignedXmlDocumentString );
using ( MemoryStream ms = new MemoryStream( stringData ) )
return VerifyXmlFromStream( ms );
}
在该步骤中,我正在改变编码,因此文档内容与原始内容不同。相当新手的错误。
解决方案:
public static bool VerifyXml(XmlDocument SignedXmlDocument)
{
byte[] stringData = Encoding.Default.GetBytes(SignedXmlDocument.OuterXml);
using (MemoryStream ms = new MemoryStream(stringData))
return VerifyXmlFromStream(ms);
}