Я пытался заставить поддержку 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;
}