Skip to content

Instantly share code, notes, and snippets.

@SumindaD
Created January 5, 2020 06:41
Show Gist options
  • Save SumindaD/02572e6bde6049a7e35e2b2fe3151992 to your computer and use it in GitHub Desktop.
Save SumindaD/02572e6bde6049a7e35e2b2fe3151992 to your computer and use it in GitHub Desktop.
/// <summary>
/// Sign the xml image document using private key certificate
/// </summary>
/// <param name="xmlDocumentBuffer">Byte[] of the xml image document</param>
/// <param name="certificate">X509Certificate2 private key certificate to sign the xml document</param>
/// <param name="signedXMLPath">Path to save the signed xml document</param>
private static void SignXMLDocument(byte[] xmlDocumentBuffer, X509Certificate2 certificate, string signedXMLPath)
{
// Load xmlDocument data in to an XML Document
XmlDocument xmlDocument = new XmlDocument();
string xml = Encoding.UTF8.GetString(xmlDocumentBuffer);
xmlDocument.LoadXml(xml);
// Sign the XML document using the certificate private key
using (var rsaKey = certificate.PrivateKey)
{
var signedXml = new SignedXml(xmlDocument);
signedXml.SigningKey = rsaKey;
var reference = new Reference();
reference.Uri = "";
var env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
signedXml.AddReference(reference);
signedXml.ComputeSignature();
var xmlDigitalSignature = signedXml.GetXml();
xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true));
xmlDocument.Save(signedXMLPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment