2017-08-07 56 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的答案。 –

相關問題