2017-08-07 77 views
0

我必须签署一些XML。我发现了很多使用“SignedXml”类签名XML的例子,并且在需要签名的XML末尾添加签名的XmlElement。SignatureType class

像这样:

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

但是使用这个示例中的签名是我的对象的序列化之后进行。我想用类“SignatureType”这是对象的内部创建(他们是通过使用包含类“SignatureType”的xmldsig-core-schema.xsd中的xsds文件创建),然后仅发送可序列化的对象。

Somenthing这样的:

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” 正确使用。有人知道我在哪里可以找到如何做到这一点的例子?

回答

1

您应该寻找封装的,封装和分离的XML签名,它们的区别以及对您的目的有用的内容。

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

+0

这是真的,封套签名实现可以用于我最终需要签名的其他xml。 Tks的答案。 –