Пример #1
0
        static string SignXml(Certificate certificate, string sourcePath, string signedPath)
        {
            // Create a new XML document.
            XmlDocument xmlDoc = new XmlDocument();

            // Load an XML file into the XmlDocument object.
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(sourcePath);

            var signatureType = SignatureType.Enveloped;

            // Sign the XML document.
            xmlDoc = XmlDsig.Sign(xmlDoc, certificate.X509Certificate2, signatureType);

            // Save the document.
            xmlDoc.Save(signedPath);
            return($"XML file signed, path:{signedPath}");
        }
Пример #2
0
        static string VerifyXmlSignature(string signedPath)
        {
            var status = new StringBuilder();

            // Create a new XML document.
            XmlDocument xmlDoc = new XmlDocument();

            // Load an XML file into the XmlDocument object.
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(signedPath);

            status.AppendLine("Verifying signature...");

            // Verify the signature of the signed XML.
            var signatureVerificationResult = XmlDsig.Verify(xmlDoc);

            // Verify the certificate
            var certificateVerificationResult = CertificateUtility.Verify(signatureVerificationResult.Certificate);

            // Display the results of the signature verification to the console.
            if (signatureVerificationResult.IsSignatureValid)
            {
                status.AppendLine("The XML signature is valid.");
                status.AppendFormat("Is certificate valid: \t{0}{1}", certificateVerificationResult.IsCertificateValid, Environment.NewLine);

                var certificate = signatureVerificationResult.Certificate;
                status.AppendFormat("Name: \t{0}{1}", certificate.FriendlyName, Environment.NewLine);
                status.AppendFormat("Subject: \t{0}{1}", certificate.Subject, Environment.NewLine);
                status.AppendFormat("Version: \t{0}{1}", certificate.Version, Environment.NewLine);
                status.AppendFormat("Serial Number: \t{0}{1}", certificate.SerialNumber, Environment.NewLine);

                status.AppendFormat("Not Before: \t{0}{1}", certificate.NotBefore, Environment.NewLine);
                status.AppendFormat("Not After: \t{0}{1}", certificate.NotAfter, Environment.NewLine);
            }
            else
            {
                status.AppendLine("The XML signature is not valid.");
                status.AppendFormat("Message: \t{0}{1}", signatureVerificationResult.ErrorMessage, Environment.NewLine);
            }

            return(status.ToString());
        }