1

我正在使用XmlDsigEnvelopedSignatureTransform 使用 RSA 私钥对 XML 文件进行数字签名。

但是,我真正想要的是使用“封装”签名对 xml 进行签名。.NET 对此有本机支持吗?

顺便说一句,这是我的代码:

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));

}
4

1 回答 1

4

如果您的签名不是签名数据的子元素,则不需要信封签名转换。

因此,只需跳过XmlDsigEnvelopedSignatureTransform并执行签名,否则:

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();
} 
于 2012-02-09T19:25:02.603 回答