签名类型 class

SignatureType class

我必须签署一些 XML。我找到了很多关于如何使用 "SignedXml" class 签署 XML 的示例,并在需要的 XML 末尾添加签名的 XmlElement被签名。

像这样:

SignedXml signedXml = new SignedXml(xmlDoc);

// Add the key to the SignedXml document.
signedXml.SigningKey = certificado.PrivateKey;

// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";

// Add an enveloped transformation to the reference.
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigC14NTransform());

// Add the reference to the SignedXml object.
signedXml.AddReference(reference);

KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(certificado));
signedXml.KeyInfo = keyInfo;

// Compute the signature.
signedXml.ComputeSignature();

// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();

// Append the element to the XML document.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

但是使用这个例子,签名是在我的对象序列化之后完成的。我想使用在对象内部创建的 class "SignatureType"(它们是通过使用创建的xsds 文件沿 xmldsig-core-schema.xsd,其中包含 class "SignatureType" ),然后只发送可序列化的对象。

像这样:

var myObject = new MyObject();

var signature = new SignatureType();
signature.SignedInfo = new SignedInfoType();
signature.SignedInfo.CanonicalizationMethod = new CanonicalizationMethodType();
signature.SignedInfo.CanonicalizationMethod.Algorithm = "Algorithm";
signature.SignedInfo.SignatureMethod = new SignatureMethodType();
signature.SignedInfo.SignatureMethod.Algorithm = "Algorithm";
signature.SignedInfo.Reference = new[] { new ReferenceType { DigestMethod = new DigestMethodType { Algorithm = "Algorithm" }, DigestValue = new byte[] { 4, 5, 6, 8 } } };
signature.SignatureValue = new SignatureValueType();

myObject.Signature = signature;

using (Stream stream = File.Open(file, FileMode.Create))
{
    var serializer = new XmlSerializer(typeof(MyObject));
    serializer.Serialize(stream, myObject);
    stream.Flush();
    stream.Close();
}

但我现在真的不知道如何正确使用"SignatureType"。有人知道我在哪里可以找到如何执行此操作的示例吗?

您应该寻找包封的、包封的和分离的 XML 签名,它们的区别以及对您的目的有用的东西。

多年来,我们一直使用封装签名 (HMACSHA256),就像您在上面的第一个示例中那样。这对我们来说是一个很好的解决方案,因为它很灵活。签名作为根的子项附加,因此 .NET class 的 XmlSerializer 不受影响,可以在附加步骤中检查签名。或者可以忽略。