tags:

views:

197

answers:

1

I've been trying to get the XMLDSIG support in .NET to behave properly, more specifically the SignedXml class. I'm implementing a third party service and they've just recently started requiring that all messages have to be digitally signed...

My problem is that, I can't seem to generate valid signatures. Both the third party service, and an online signature verifier I found, report the signature as invalid. The verification service (http://www.aleksey.com/xmlsec/xmldsig-verifier.html) reports that there's a mismatch between the digest and the data, and I've so far been unable to figure out what I'm doing wrong.

Here's the relevant code - hopefully someone will be able to spot my mistake;

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;
}
+1  A: 

In case anyone is interested, I solved the problem and wrote about it on my blog: http://thomasjo.com/blog/archive/xmldsig-in-the-net-framework/

Thomas J
Great work! I think your article is going to help me a lot! I need to use the "enveloped" type, and the existent documentation was horrible...
Juan Calero