using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
public class SignVerifyEnvelope
public static void Main(String[] args)
RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
CreateSomeXml("Example.xml");
Console.WriteLine("New XML file created.");
SignXmlFile("Example.xml", "signedExample.xml", Key);
Console.WriteLine("XML file signed.");
Console.WriteLine("Verifying signature...");
bool result = VerifyXmlFile("SignedExample.xml", Key);
Console.WriteLine("The XML signature is valid.");
Console.WriteLine("The XML signature is not valid.");
catch(CryptographicException e)
Console.WriteLine(e.Message);
public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
XmlDocument doc = new XmlDocument();
doc.Load(new XmlTextReader(FileName));
SignedXml signedXml = new SignedXml(doc);
signedXml.SigningKey = Key;
Reference reference = new Reference();
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
signedXml.AddReference(reference);
signedXml.ComputeSignature();
XmlElement xmlDigitalSignature = signedXml.GetXml();
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
if (doc.FirstChild is XmlDeclaration)
doc.RemoveChild(doc.FirstChild);
XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
public static Boolean VerifyXmlFile(String Name, RSA Key)
XmlDocument xmlDocument = new XmlDocument();
SignedXml signedXml = new SignedXml(xmlDocument);
XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
signedXml.LoadXml((XmlElement)nodeList[0]);
return signedXml.CheckSignature(Key);
public static void CreateSomeXml(string FileName)
XmlDocument document = new XmlDocument();
XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");
node.InnerText = "Example text to be signed.";
document.AppendChild(node);
XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));