Я пытался добиться, чтобы поддержка XMLDSIG в .NET работала должным образом, в частности класс SignedXml. Я внедряю стороннюю службу, и они только недавно начали требовать, чтобы все сообщения были подписаны цифровой подписью ...
Моя проблема в том, что я не могу генерировать действительные подписи. Обнаруженная мной сторонняя служба и средство проверки подписи в Интернете сообщают, что подпись недействительна. Служба проверки (http://www.aleksey.com/xmlsec/xmldsig-verifier.html) сообщает, что существует несоответствие между дайджестом и данными, и я до сих пор не смог выяснить, что я делаю неправильно.
Вот соответствующий код - надеюсь, кто-то сможет распознать мою ошибку;
public static XDocument SignDocument(XDocument originalDocument, X509Certificate2 certificate)
{
var document = new XmlDocument();
document.LoadXml(originalDocument.ToString(SaveOptions.DisableFormatting));
if (document.DocumentElement == null)
throw new InvalidOperationException("Invalid XML document; no root element found.");
var signedDocument = new SignedXml(document);
Reference signatureReference = GetSignatureReference();
KeyInfo certificateKeyInfo = GetCertificateKeyInfo(certificate);
var dataObject = new DataObject("", "text/xml", "utf-8", document.DocumentElement);
signedDocument.AddReference(signatureReference);
signedDocument.AddObject(dataObject);
signedDocument.SigningKey = certificate.PrivateKey;
signedDocument.KeyInfo = certificateKeyInfo;
signedDocument.ComputeSignature();
return XDocument.Parse(signedDocument.GetXml().OuterXml, LoadOptions.PreserveWhitespace);
}
private static Reference GetSignatureReference()
{
var signatureReference = new Reference("");
signatureReference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
return signatureReference;
}
private static KeyInfo GetCertificateKeyInfo(X509Certificate certificate)
{
var certificateKeyInfo = new KeyInfo();
certificateKeyInfo.AddClause(new KeyInfoX509Data(certificate));
return certificateKeyInfo;
}