2

I'm using the XmlDsigEnvelopedSignatureTransform to digitally sign an XML file using an RSA private key.

However, what I really want is to sign the xml using an "enveloping" signature. Does .NET have native support for that?

By the way, here's my code:

public static void SignXml(XmlDocument xmlDoc, RSA key)
{
    // Check arguments.
    if (xmlDoc == null)
        throw new ArgumentException("xmlDoc");
    if (key == null)
        throw new ArgumentException("Key");

    SignedXml xml = new SignedXml(xmlDoc);            
    xml.SigningKey = key;

    Reference reference = new Reference();
    reference.Uri = "";

    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true);                        

    reference.AddTransform(env);

    xml.AddReference(reference);

    xml.ComputeSignature();

    XmlElement element = xml.GetXml();

    MessageBox.Show(element.OuterXml);

    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(element, true));

}
Ian
  • 5,625
  • 11
  • 57
  • 93

1 Answers1

4

If your signature is not a sub-element of the signed data you do not need the Enveloped Signature Transform.

So just skip the XmlDsigEnvelopedSignatureTransform and perform the signature as you would otherwise:

public XmlElement SignXml(XmlDocument xmlDoc, RSA key)
{
  SignedXml xml = new SignedXml();            
  xml.SigningKey = key;

  // Add the data to be signed as a sub-element of the Signature-element:
  DataObject dataObject = new DataObject();
  dataObject.Data = xmlDoc.ChildNodes;
  dataObject.Id = "doc";
  xml.AddObject(dataObject);

  // Add a reference to the signed data:
  Reference reference = new Reference();
  reference.Uri = "#doc";
  xml.AddReference(reference);  

  // Perform the signature. No transforms are needed.
  xml.ComputeSignature();

  return xml.GetXml();
} 
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189