public static bool VerifySignature(string xml)
            {
                if (xml == null) throw new ArgumentNullException("xml");

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.LoadXml(xml);

                // If there's no signature => return that we are "valid"
                XmlNode signatureNode = findSignatureElement(doc);
                if (signatureNode == null) return true;

                SignedXml signedXml = new SignedXml(doc);
                signedXml.LoadXml((XmlElement)signatureNode);

                //var x509Certificates = signedXml.KeyInfo.OfType<KeyInfoX509Data>();
                //var certificate = x509Certificates.SelectMany(cert => cert.Certificates.Cast<X509Certificate2>()).FirstOrDefault();

                //if (certificate == null) throw new InvalidOperationException("Signature does not contain a X509 certificate public key to verify the signature");
                //return signedXml.CheckSignature(certificate, true);

                return signedXml.CheckSignature();
            }
Пример #2
0
            public bool IsValid()
            {
                bool status = false;

                XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
                manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
                XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager);

                SignedXml signedXml = new SignedXml(xmlDoc);
                signedXml.LoadXml((XmlElement)nodeList[0]);
                return signedXml.CheckSignature(certificate.cert, true);
            }
Пример #3
0
        /// <summary>
        /// Verifies if the signature of the file is valid
        /// </summary>
        /// <param name="signedXml">The path to the signed file</param>
        /// <returns>True if valid or false if not valid</returns>
        public static bool CheckSignature(string signedXml)
        {
            byte[] xml = File.ReadAllBytes(signedXml);
            using (MemoryStream stream = new MemoryStream(xml))
            {
                // go to the beginning of the stream
                stream.Flush();
                stream.Position = 0;

                // create new XmlDocument from stream
                XmlDocument doc = new XmlDocument()
                {
                    PreserveWhitespace = true
                };
                doc.Load(stream);

                // get signature node
                XmlNodeList nodeList = doc.GetElementsByTagName("Signature", "*");
                if (nodeList.Count != 1)
                {
                    // invalid file
                    throw new Exception("Signature is missing or multiple signatures found!");
                }

                // get signature node
                XmlNodeList keyInfoNode = doc.GetElementsByTagName("KeyInfo", "*");
                if (keyInfoNode.Count != 1)
                {
                    // invalid file
                    throw new Exception("KeyInfo element is required to validate signature!");
                }

                // create SignedXml and load it with data
                SignedXml signed = new SignedXml(doc);
                signed.LoadXml(nodeList[0] as XmlElement);
                XmlElement root = doc.DocumentElement;

                // check the reference in the signature
                CheckSignatureReference(signed, root);
                // check the signature
                return(signed.CheckSignature());
            }
        }
Пример #4
0
        private static bool VerifyXml(string signedXmlText, X509Certificate2 certificate)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(signedXmlText);

            SignedXml signedXml     = new SignedXml(xmlDoc);
            var       signatureNode = (XmlElement)xmlDoc.GetElementsByTagName("Signature")[0];

            signedXml.LoadXml(signatureNode);

            // Note: `verifySignatureOnly: true` should not be used in the production
            //       without providing application logic to verify the certificate.
            // This test bypasses certificate verification because:
            // - certificates expire - test should not be based on time
            // - we cannot guarantee that the certificate is trusted on the machine
            return(signedXml.CheckSignature(certificate, verifySignatureOnly: true));
        }
Пример #5
0
        private bool CheckIdxSignature(XmlDocument document, XmlElement signature)
        {
            var signedXml = new SignedXml(document);

            signedXml.LoadXml(signature);

            X509Certificate2 incomingCertificate = null;

            foreach (object o in signedXml.KeyInfo)
            {
                dynamic clause = (KeyInfoClause)o;
                Type    t      = clause.GetType();
                if (t.GetProperties().Any(p => p.Name.Equals("Value")) && clause.Value.ToUpper() == configuration.Acquirer.Certificate.Thumbprint.ToUpper())
                {
                    incomingCertificate = certificateLoader.Load(configuration.Acquirer.Certificate.Thumbprint);
                    break;
                }

                if (!string.IsNullOrEmpty(configuration.Acquirer.AlternateCertificate.Thumbprint))
                {
                    if (t.GetProperties().Any(p => p.Name.Equals("Value")) && clause.Value.ToUpper() == configuration.Acquirer.AlternateCertificate.Thumbprint.ToUpper())
                    {
                        incomingCertificate = certificateLoader.Load(configuration.Acquirer.AlternateCertificate.Thumbprint);
                        break;
                    }
                }
            }

            if (incomingCertificate == null)
            {
                logger.LogDebug("the certificate used for signing is not the same as the one in the configuration");
                return(false);
            }

            if (!signedXml.CheckSignature(incomingCertificate, true))
            {
                logger.LogDebug("signature is not valid");
                return(false);
            }

            logger.LogDebug("signature is valid");
            return(true);
        }
Пример #6
0
        public static bool IsSignatureValid(this XmlDocument document, RSA publicKey)
        {
            var signedXml = new SignedXml(document);
            var nodeList  = document.GetSignatures();

            if (nodeList.Count == 0)
            {
                throw new CryptographicException("No Signature was found in the document.");
            }

            if (nodeList.Count != 1)
            {
                throw new CryptographicException("More that one signature was found for the document.");
            }

            signedXml.LoadXml((XmlElement)nodeList[0]);

            return(signedXml.CheckSignature(publicKey));
        }
Пример #7
0
        private bool SignVerify(XmlDocument document)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document), "XML document is null.");
            }

            SignedXml   signed = new SignedXml(document);
            XmlNodeList list   = document.GetElementsByTagName("Signature");

            if (list == null || list.Count == 0)
            {
                throw new CryptographicException($"This XML doesn't contain a signature.");
            }
            if (list.Count > 1)
            {
                throw new CryptographicException($"This XML contains more than one signature.");
            }

            signed.LoadXml((XmlElement)list[0]);

            List <X509Certificate2> certs = new List <X509Certificate2>();

            foreach (KeyInfoX509Data clause in signed.KeyInfo)
            {
                foreach (X509Certificate2 cert in clause.Certificates)
                {
                    certs.Add(cert);
                }
            }

            if (certs.Count == 0)
            {
                throw new CryptographicException($"This XML doesn't contain a certificate.");
            }

            if (certs.Count > 1)
            {
                throw new CryptographicException($"This XML contains more than one certificate.");
            }

            return(signed.CheckSignature(certs[0], !validateCertCfg.Checked));
        }
        public static bool ValidateSignature(XmlDocument xmlDoc, RSA publicKey)
        {
            //try
            //{
            xmlDoc.PreserveWhitespace = true;

            var signedXmlObj = new SignedXml(xmlDoc);

            var nodeList = xmlDoc.GetElementsByTagName("Signature");

            signedXmlObj.LoadXml((XmlElement)nodeList[0]);

            return(signedXmlObj.CheckSignature(publicKey));
            //}
            //catch
            //{
            //    return false;
            //}
        }
Пример #9
0
        public void XmlHelpers_Sign()
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml("<root ID=\"rootElementId\"><content>Some Content</content></root>");

            xmlDoc.Sign(TestCert);

            var signature = xmlDoc.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl];

            signature["SignedInfo", SignedXml.XmlDsigNamespaceUrl]
            ["Reference", SignedXml.XmlDsigNamespaceUrl].Attributes["URI"].Value
            .Should().Be("#rootElementId");

            var signedXml = new SignedXml(xmlDoc);

            signedXml.LoadXml(signature);
            signedXml.CheckSignature(TestCert, true).Should().BeTrue();
        }
Пример #10
0
        // Verify the signature of an XML file against an asymmetric
        // algorithm and return the result.
        private static bool VerifyXml(XmlDocument doc, RSA key)
        {
            // Check arguments.
            if (doc == null)
            {
                throw new ArgumentException("Doc");
            }

            if (key == null)
            {
                throw new ArgumentException("Key");
            }

            // Create a new SignedXml object and pass it
            // the XML document class.
            var signedXml = new SignedXml(doc);

            // Find the "Signature" node and create a new
            // XmlNodeList object.
            var nodeList = doc.GetElementsByTagName("Signature");

            // Throw an exception if no signature was found.
            if (nodeList.Count <= 0)
            {
                throw new CryptographicException("Verification failed: No Signature was found in the document.");
            }

            // This example only supports one signature for
            // the entire XML document.  Throw an exception
            // if more than one signature was found.
            if (nodeList.Count >= 2)
            {
                throw new CryptographicException(
                          "Verification failed: More that one signature was found for the document.");
            }

            // Load the first <signature> node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            // Check the signature and return the result.
            return(signedXml.CheckSignature(key));
        }
        private static bool VerifyXmlSignature(string xmlString, string publicKey)
        {
            using (var keyReader = new StringReader(publicKey))
            {
                var pemReader = new PemReader(keyReader);

                RsaKeyParameters parameters = (RsaKeyParameters)pemReader.ReadObject();
                RSAParameters    rParams    = new RSAParameters();
                rParams.Modulus  = parameters.Modulus.ToByteArray();
                rParams.Exponent = parameters.Exponent.ToByteArray();

                RSA rsaKey = RSA.Create();
                rsaKey.ImportParameters(rParams);

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.LoadXml(xmlString);

                // Create a new SignedXml object and pass it the XML document class
                SignedXml signedXml = new SignedXml(xmlDoc);
                // Find the "Signature" node and create a new XmlNodeList object
                XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");

                // Throw an exception if no signature was found
                if (nodeList.Count <= 0)
                {
                    throw new CryptographicException("Verification failed: No Signature was found in the document.");
                }

                // Throw an exception if more than one signature was found
                if (nodeList.Count >= 2)
                {
                    throw new CryptographicException("Verification failed: More that one signature was found for the document.");
                }

                // Load the first <signature> node
                signedXml.LoadXml((XmlElement)nodeList[0]);

                // Check the signature and return the result
                return(signedXml.CheckSignature(rsaKey));
            }
        }
Пример #12
0
        /// <summary>
        /// Verify the signature of an XML file
        /// </summary>
        /// <param name="fileName">Filename</param>
        /// <returns>True or False</returns>
        public static Boolean VerifyXmlFile(String fileName)
        {
            // Check the args.
            if (null == fileName)
            {
                throw new ArgumentNullException("FileName");
            }

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

            xmlDocument.PreserveWhitespace = true;

            // check the file exists
            if (!(System.IO.File.Exists(fileName)))
            {
                throw new ArgumentNullException("File not found");
            }

            // Load the passed XML file into the document.
            xmlDocument.Load(fileName);

            // Create a new SignedXml object and pass it
            // the XML document class.
            SignedXml signedXml = new SignedXml(xmlDocument);

            // Find the "Signature" node and create a new
            // XmlNodeList object.
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

            // nodeList shoud be empty if there is no sig block (cngCA case)
            if (nodeList.Count == 0)
            {
                return(true);
            }

            // Load the signature node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            // Check the signature and return the result.
            return(signedXml.CheckSignature());
        }
Пример #13
0
            public static bool TryVerifyXml(string xml, out string failureMessage)
            {
                if (!TryLoadXmlDocument(xml, out var doc))
                {
                    failureMessage = "The text provided could not be parsed as XML";
                    return(false);
                }

                using (var rsa = new RSACryptoServiceProvider())
                {
                    var parameters = new RSAParameters
                    {
                        Modulus  = Convert.FromBase64String(Modulus),
                        Exponent = Convert.FromBase64String(Exponent)
                    };

                    rsa.ImportParameters(parameters);

                    var nsMgr = new XmlNamespaceManager(doc.NameTable);
                    nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#");

                    var signedXml = new SignedXml(doc);
                    var signature = (XmlElement)doc.SelectSingleNode("//sig:Signature", nsMgr);

                    if (signature == null)
                    {
                        failureMessage = "XML is invalid because does not have an XML signature";
                        return(false);
                    }

                    signedXml.LoadXml(signature);

                    if (!signedXml.CheckSignature(rsa))
                    {
                        failureMessage = "XML is invalid because it failed the signature check";
                        return(false);
                    }

                    failureMessage = null;
                    return(true);
                }
            }
Пример #14
0
        // Verify the signature of an XML file against an asymmetric
        // algorithm and return the result.
        public static Boolean VerifyXmlSignature(XmlDocument doc)
        {
            RSACryptoServiceProvider key = new RSACryptoServiceProvider();
            XmlElement keyNode           = (XmlElement)CollectionUtils.FirstElement(doc.GetElementsByTagName("KeyValue"));

            // Use the key in the document to verify
            key.FromXmlString(keyNode.InnerXml);

            // Check arguments.
            if (doc == null)
            {
                throw new ArgumentException("doc");
            }

            // Create a new SignedXml object and pass it
            // the XML document class.
            SignedXml signedXml = new SignedXml(doc);

            // Find the "Signature" node and create a new
            // XmlNodeList object.
            XmlNodeList nodeList = doc.GetElementsByTagName("Signature");

            // Throw an exception if no signature was found.
            if (nodeList.Count <= 0)
            {
                throw new CryptographicException("Verification failed: No Signature was found in the document.");
            }

            // This example only supports one signature for
            // the entire XML document.  Throw an exception
            // if more than one signature was found.
            if (nodeList.Count >= 2)
            {
                throw new CryptographicException("Verification failed: More that one signature was found for the document.");
            }

            // Load the first <signature> node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            // Check the signature and return the result.
            return(signedXml.CheckSignature(key));
        }
        private bool CheckIdxSignature(XmlDocument document, XmlElement signature)
        {
            var signedXml = new SignedXml(document);

            signedXml.LoadXml(signature);

            X509Certificate2 incomingCertificate = null;

            foreach (var keyInfo in signedXml.KeyInfo.OfType <KeyInfoName>())
            {
                var keyInfoValue = keyInfo.Value;

                if (!string.IsNullOrEmpty(keyInfoValue))
                {
                    if (string.Compare(keyInfoValue, _configuration.RoutingServiceCertificate.Thumbprint, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        incomingCertificate = _configuration.RoutingServiceCertificate;
                        break;
                    }
                    if (string.Compare(keyInfoValue, _configuration.AlternateRoutingServiceCertificate?.Thumbprint, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        incomingCertificate = _configuration.AlternateRoutingServiceCertificate;
                        break;
                    }
                }
            }

            if (incomingCertificate == null)
            {
                _logger.Log("the certificate used for signing is not the same as the one in the configuration");
                return(false);
            }

            if (!signedXml.CheckSignature(incomingCertificate, true))
            {
                _logger.Log("signature is not valid");
                return(false);
            }

            _logger.Log("signature is valid");
            return(true);
        }
Пример #16
0
        // Verify the signature of an XML file against an asymmetric
        // algorithm and return the result.
        public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
        {
            // Check arguments.
            if (Doc == null)
            {
                throw new ArgumentException("Doc");
            }
            if (Key == null)
            {
                throw new ArgumentException("Key");
            }

            // Create a new SignedXml object and pass it
            // the XML document class.
            SignedXml signedXml = new SignedXml(Doc);

            // Find the "Signature" node and create a new
            // XmlNodeList object.
            XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

            // Throw an exception if no signature was found.
            if (nodeList.Count <= 0)
            {
                TraceHelper.TraceWarning(TraceSwitches.TfsDeployer, "Verification failed: No Signature was found in the document.");
                return(false);
            }

            // This example only supports one signature for
            // the entire XML document.  Throw an exception
            // if more than one signature was found.
            if (nodeList.Count >= 2)
            {
                TraceHelper.TraceWarning(TraceSwitches.TfsDeployer, "Verification failed: More that one signature was found for the document.");
                return(false);
            }

            // Load the first <signature> node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            // Check the signature and return the result.
            return(signedXml.CheckSignature(Key));
        }
Пример #17
0
        public bool CheckLicense(string licenseXml)
        {
            SignedXml   xml    = new SignedXml();
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(licenseXml);
            string pubKey = xmlDoc.SelectSingleNode("IGCESLicense").SelectSingleNode("PublicKey").InnerXml;
            RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

            Key.FromXmlString(pubKey);

            SignedXml   signedXml = new SignedXml(xmlDoc);
            XmlNodeList nodeList  = xmlDoc.GetElementsByTagName("Signature");

            signedXml.LoadXml((XmlElement)nodeList[0]);
            bool signature_ok = signedXml.CheckSignature(Key);

            if (signature_ok)
            {
                string sn = xmlDoc.GetElementsByTagName("序列号")[0].InnerText;
                if (cksn)
                {
                    return(GetSn() == sn);
                }
                else
                {
                    return(true);
                }
                //string cpu = xmlDoc.GetElementsByTagName("cpu")[0].InnerText ;
                //string mac = xmlDoc.GetElementsByTagName("mac")[0].InnerText ;
                //string disk = xmlDoc.GetElementsByTagName("disk")[0].InnerText ;
                //QcHardWare h=new QcHardWare();

                //if (cpu.Contains(h.GetCpuID()) == false) return false;
                //var lstdisk = h.GetDiskID().Split(';');
                //if (lstdisk.Any(t => disk.Contains(t) == false)) return false;
                //var lstmac = h.GetMacAddress().Split(';');
                //if (lstmac.Any(t => mac.Contains(t) == false)) return false;
                //return true;
            }
            return(false);
        }
Пример #18
0
        /// <summary>
        /// Verifies an element.
        /// </summary>
        /// <param name="element">Xml element.</param>
        /// <param name="signature">Signature.</param>
        /// <param name="issuerCertificates">Certificates used to verify the element.</param>
        /// <param name="thumbprint">Thumbprint used to select the right certificate.</param>
        /// <returns>Whether or not the element is verified.</returns>
        public static bool VerifyElement(
            this XmlElement element,
            XmlElement signature,
            IEnumerable <X509Certificate2> issuerCertificates,
            string thumbprint)
        {
            if (!issuerCertificates.Any(c => c.Thumbprint == thumbprint))
            {
                return(false);
            }

            var certificate = issuerCertificates
                              .First(ic => ic.Thumbprint == thumbprint);

            var signedXml = new SignedXml(element);

            signedXml.LoadXml(signature);

            return(signedXml.CheckSignature(certificate.GetRSAPublicKey()));
        }
Пример #19
0
        /// <summary>SignedXml検証メソッド</summary>
        /// <param name="signedXmlString">SignedXml</param>
        /// <param name="referenceId">署名対象ノードのID値(「#」は含まない)</param>
        /// <param name="preserveWhitespace">SignedXmlの空白・改行を保持する()・しない(false)</param>
        /// <returns>署名の検証結果</returns>
        public bool Verify(string signedXmlString, string referenceId, bool preserveWhitespace = false)
        {
            // 初期処理
            // - XmlDocument
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = preserveWhitespace;
            xmlDoc.LoadXml(signedXmlString);

            // 子ノード のXML検証
            XmlNode targetNode = XmlLib.GetXmlNodeById(xmlDoc, referenceId);

            // 署名ノードの直下のSignatureを取り出して、signedXml.LoadXmlする。
            SignedXml signedXml = new SignedXml(targetNode.OwnerDocument);

            signedXml.LoadXml(targetNode["Signature"] as XmlElement);

            // XML検証
            return(signedXml.CheckSignature(this._rsa));
        }
Пример #20
0
        private MetadataDocument()
        {
            Document = new XmlDocument {
                PreserveWhitespace = true
            };
            X509Certificate2 cert     = new X509Certificate2(Convert.FromBase64String(Settings.Default.SigningCert));
            HttpWebRequest   request  = WebRequest.CreateHttp(Settings.Default.metadataUrl);
            HttpWebResponse  response = (HttpWebResponse)request.GetResponse();

            using (Stream receiveStream = response.GetResponseStream())
            {
                Document.Load(receiveStream);
                SignedXml   signedXml = new SignedXml(Document);
                XmlNodeList nodeList  = Document.GetElementsByTagName("Signature", @"http://www.w3.org/2000/09/xmldsig#");
                signedXml.LoadXml((XmlElement)nodeList[0]);
                SignatureValid = signedXml.CheckSignature(cert, true);
            }

            _metadataLoadedUtc = DateTime.UtcNow;
        }
Пример #21
0
        /// <summary>
        /// Determines whether the digital signature of an XML is valid.
        /// </summary>
        /// <param name="xml">The signed XML.</param>
        /// <returns>true if the signature is valid; otherwise, false.</returns>
        /// <exception cref="NotSupportedException"></exception>
        public bool VerifySignature(XElement xml)
        {
#if NET46
            ValidateNull(xml, nameof(xml));
            ValidateNull(Verifier, nameof(Verifier));

            var document = GetXmlDocument(xml);
            var nodeList = document.GetElementsByTagName("Signature");
            if (nodeList.Count == 0)
            {
                throw new CryptographicException(NoSignature);
            }
            var signedXml = new SignedXml(document);
            signedXml.LoadXml((XmlElement)nodeList[0]);

            return(signedXml.CheckSignature(Verifier.PublicKey.Key));
#else
            throw new NotSupportedException(NotSupportedXmlSignature);
#endif
        }
Пример #22
0
        private static X509Certificate2 GetCertificateFromResponse(SigneringResponse response)
        {
            var signatureProof = Encoding.UTF8.GetString(Convert.FromBase64String(response.SignedSignatureProof));

            var doc = new XmlDocument()
            {
                PreserveWhitespace = true
            };

            doc.LoadXml(signatureProof);
            var signedXml = new SignedXml(doc);

            var nodeList = doc.GetElementsByTagName("Signature");

            signedXml.LoadXml((XmlElement)nodeList[0]);

            var cert = (X509Certificate2)signedXml.Signature.KeyInfo.Cast <KeyInfoX509Data>().First().Certificates[0];

            return(cert);
        }
Пример #23
0
        public void GeneratedXmlIsCorrectlySigned()
        {
            var key       = new RSACryptoServiceProvider();
            var generator = new LicenseGenerator(key);

            var rawXml = generator.GenerateSignedXml(new LicenseDetails());

            var        doc    = new XmlDocument();
            TextReader reader = new StringReader(rawXml);

            doc.Load(reader);

            var signedXml = new SignedXml(doc);
            var nodeList  = doc.GetElementsByTagName("Signature");

            signedXml.LoadXml((XmlElement)nodeList[0]);
            var result = signedXml.CheckSignature(key);

            Assert.IsTrue(result, "Verification of xml signature failed");
        }
Пример #24
0
        public static void ParseSignature(XmlElement signatureXmlElement)
        {
            SignedXml signedXml = new SignedXml();

            signedXml.LoadXml(((System.Xml.XmlElement)(signatureXmlElement)));


            RSA key = null;
            var e   = signedXml.KeyInfo.GetEnumerator();

            while (e.MoveNext())
            {
                X509Certificate2 cert = (X509Certificate2)((System.Security.Cryptography.Xml.KeyInfoX509Data)e.Current).Certificates[0];
                var isValidSSOCert    = ValidateCertificate(cert);

                key = (RSA)((System.Security.Cryptography.RSACryptoServiceProvider)(cert.PublicKey.Key));

                break;
            }
        }
        private bool verificarAssinatura(ArquivoDTO arquivo)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(arquivo.streamAssinatura);

                SignedXml signedXml = new SignedXml();

                XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

                signedXml.LoadXml((XmlElement)nodeList[0]);

                return(signedXml.CheckSignature());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #26
0
        internal static bool VerifySignature(XmlElement el)
        {
            var cspParams = new CspParameters();

            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
            var rsaKey = new RSACryptoServiceProvider(cspParams);

            var assertionElement = el.LocalName == "Assertion" ? el : TokenHelper.GetElement("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion", el);
            var signEl           = TokenHelper.GetElement("Signature", "http://www.w3.org/2000/09/xmldsig#", el);
            var certEl           = TokenHelper.GetElement("X509Certificate", "http://www.w3.org/2000/09/xmldsig#", signEl);

            var signedXml = new SignedXml(assertionElement);

            var dcert2 = new X509Certificate2(Convert.FromBase64String(certEl.InnerText));

            signedXml.LoadXml(signEl);
            var valid = signedXml.CheckSignature(dcert2, true);

            return(valid);
        }
Пример #27
0
        /// <summary>
        /// Idicates whether the supplied Document is valid based on the provided Key.
        /// </summary>
        public static bool VerifySignedXmlDocument(RSA SigningPubKey, XmlDocument Document)
        {
            SignedXml SignedDoc = new SignedXml(Document);

            try
            {
                // Find signature node
                XmlNode sig = Document.GetElementsByTagName(XML_SIGNED_DOC_FLD_SIGNATURE, SignedXml.XmlDsigNamespaceUrl)[0];
                SignedDoc.LoadXml((XmlElement)sig);
            }
            catch
            {
                // Not signed!
                return(false);
            }

            var Result = SignedDoc.CheckSignature(SigningPubKey);

            return(Result);
        }
Пример #28
0
        /// <summary>
        /// Returns the KeyInfo element that is included with the signature in the document.
        /// </summary>
        /// <param name="doc">The doc.</param>
        /// <returns>The signature <see cref="KeyInfo"/>.</returns>
        /// <exception cref="InvalidOperationException">if the document is not signed.</exception>
        public static KeyInfo ExtractSignatureKeys(XmlDocument doc)
        {
            CheckDocument(doc);
            if (doc.DocumentElement != null)
            {
                var signedXml = new SignedXml(doc.DocumentElement);

                var nodeList = doc.GetElementsByTagName(Schema.XmlDSig.Signature.ElementName, Saml20Constants.Xmldsig);
                if (nodeList.Count == 0)
                {
                    throw new InvalidOperationException("The XmlDocument does not contain a signature.");
                }

                signedXml.LoadXml((XmlElement)nodeList[0]);

                return(signedXml.KeyInfo);
            }

            return(null);
        }
Пример #29
0
        private static void ValidateSignedXml(XmlDocument doc)
        {
            // public key, has no password
            var pemPath    = "files/modotech-test-cert-public.pem";
            var publicCert = new X509Certificate2(pemPath);

            try
            {
                var signedXml     = new SignedXml(doc);
                var signatureNode = doc.GetElementsByTagName("Signature")[0];
                signedXml.LoadXml((XmlElement)signatureNode);

                var isValid = signedXml.CheckSignature(publicCert, true);
                Console.WriteLine("Document validity is {0}", isValid);
            }
            catch
            {
                Console.WriteLine("Failed to validate");
            }
        }
Пример #30
0
        /// <summary>
        /// Verifies the specified XML document signature.
        /// </summary>
        /// <param name="xmlDocument">The XML document.</param>
        /// <param name="certificate">The certificate.</param>
        /// <param name="signEl">The signature element.</param>
        ///<returns>True if the signature is valid and placed properly, false otherwise</returns>
        public static bool CheckSignature(XmlDocument xmlDocument, X509Certificate2 certificate, XmlElement signEl)
        {
            var rsaKey = certificate.GetRSAPublicKey();

            if (signEl == null || signEl.LocalName != "Signature")
            {
                return(false);
            }

            var signedXml = new SignedXml(xmlDocument);

            signedXml.LoadXml(signEl);

            if (signedXml.CheckSignature(rsaKey))
            {
                return(AlgorithmsRegexEnvelopedSignature.All(regex => regex.IsMatch(signEl.InnerXml)));
            }

            return(false);
        }
Пример #31
0
        /// <summary>
        /// Verifies the signature.
        /// </summary>
        /// <param name="xElement">The x element.</param>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public static bool VerifySignature(XmlElement xElement, AsymmetricAlgorithm key)
        {
            var signedXml     = new SignedXml(xElement);
            var signedElement = xElement;

            if (xElement.Name != "Signature")
            {
                var nodeList = xElement.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#");
                if (nodeList == null || nodeList.Count == 0)
                {
                    return(false);
                }

                signedElement = (XmlElement)nodeList[0];
            }

            signedXml.LoadXml(signedElement);

            return(signedXml.CheckSignature(key));
        }
Пример #32
0
        /// <summary>
        /// Verifies the specified XML document signature.
        /// </summary>
        /// <param name="xmlDocument">The XML document.</param>
        /// <param name="certificate">The certificate.</param>
        /// <param name="signEl">The signature element.</param>
        ///<returns>True if the signature is valid and placed properly, false otherwise</returns>
        public static bool CheckSignature(XmlDocument xmlDocument, X509Certificate2 certificate, XmlElement signEl)
        {
            var rsaKey = (RSACryptoServiceProvider)(certificate.PublicKey.Key);

            if (signEl == null || signEl.LocalName != "Signature")
            {
                return(false);
            }

            SignedXml signedXml = new SignedXml(xmlDocument);

            signedXml.LoadXml(signEl);

            if (signedXml.CheckSignature(rsaKey))
            {
                return(AlgorithmsRegex_EnvelopedSignature.All(regex => regex.IsMatch(signEl.InnerXml)));
            }

            return(false);
        }
Пример #33
0
    // Verify the signature of an XML file against an asymmetric
    // algorithm and return the result.
    public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
    {
        // Check arguments.
        if (Doc == null)
            throw new ArgumentException("Doc");
        if (Key == null)
            throw new ArgumentException("Key");

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(Doc);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

        // Throw an exception if no signature was found.
        if (nodeList.Count <= 0)
        {
            throw new CryptographicException("Verification failed: No Signature was found in the document.");
        }

        // This example only supports one signature for
        // the entire XML document.  Throw an exception
        // if more than one signature was found.
        if (nodeList.Count >= 2)
        {
            throw new CryptographicException("Verification failed: More that one signature was found for the document.");
        }

        // Load the first <signature> node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature(Key);
    }
Пример #34
0
    // Třída ověří všechny podpisy v dokumentu
    public bool Verify(XmlDocument doc)
    {
        // definice mapování prefixů na jmenné prostory
        XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
        manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");

        // příznak validnosti podpisu
        bool validates = false;

        // vybereme všechny podpisy v dokumentu
        XmlNodeList signatures = doc.SelectNodes("/*/dsig:Signature", manager);

        // pokud by v dokumentu nebylani jeden podpis, nemůže být podpis validní
        if (signatures.Count > 0) validates = true;

        // postupné ověření všech nalezených podpisů
        for (int i = 0; i < signatures.Count; i++)
        {
            // načtení XML reprezentace podpisu
            XmlElement signatureElement = (XmlElement)signatures.Item(i);

            // načtení dokumentu do objektu pro práci s podpisy
            SignedXml signedDoc = new SignedXml(doc);

            // nastavení elementu, ve kterém se má kontrolovat podpis
            signedDoc.LoadXml(signatureElement);

            // kontrola podpisu
            if (!signedDoc.CheckSignature()) validates = false;
        }
        return validates;
    }
    static bool ValidateXml(XmlDocument receipt, X509Certificate2 certificate)
    {
        // Create the signed XML object.
        SignedXml sxml = new SignedXml(receipt);

        // Get the XML Signature node and load it into the signed XML object.
        XmlNode dsig = receipt.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0];
        if (dsig == null)
        {
            // If signature is not found return false
            System.Console.WriteLine("Signature not found.");
            return false;
        }

        sxml.LoadXml((XmlElement)dsig);

        // Check the signature
        bool isValid = sxml.CheckSignature(certificate, true);

        FieldInfo field = sxml.GetType().GetField("m_signature",
                       BindingFlags.NonPublic |
                       BindingFlags.Instance);

        var sig = (Signature)field.GetValue(sxml);
        var _ref = (Reference)sig.SignedInfo.References[0];

        //var pre = Type.GetType("System.Security.Cryptography.Xml.Utils").GetMethod("PreProcessDocumentInput");
        //pre.Invoke(null, new[] { });

        var enveloped = (XmlDsigEnvelopedSignatureTransform)_ref.TransformChain[0];

        enveloped.LoadInput(receipt);
        var outputstream = enveloped.GetOutput();

        var securityUrl = receipt.BaseURI;
        var resolver = new XmlSecureResolver(new XmlUrlResolver(), securityUrl);
        //TransformToOctetStream(Stream input, XmlResolver resolver, string baseUri)
        MethodInfo trans = _ref.TransformChain.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)[2];

        var stream = trans.Invoke(_ref.TransformChain, new object[] {receipt, resolver, securityUrl});

        var canontype = sig.GetType().Assembly.GetType("System.Security.Cryptography.Xml.CanonicalXml");
        var foo = Activator.CreateInstance(canontype, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] {receipt, resolver}, null);

        MethodInfo method = _ref.GetType().GetMethod("CalculateHashValue",
                       BindingFlags.NonPublic |
                       BindingFlags.Instance);

        FieldInfo refs = sig.GetType().GetField("m_referencedItems",
                       BindingFlags.NonPublic |
                       BindingFlags.Instance);
        var refs1 = refs.GetValue(sig);

        var res = method.Invoke(_ref, new [] {receipt, refs1});
        var str = Convert.ToBase64String((byte[])res);

        return isValid;
    }
Пример #36
0
 public static bool eval_a(string A_0, int A_1)
 {
     if (true)
     {
     }
     switch (0)
     {
     case 0:
     {
         IL_16:
         A_1 = 2;
         A_0 += eval_bw.eval_a(0);
         XmlDocument xmlDocument = new XmlDocument();
         string text = "";
         bool result;
         try
         {
             while (true)
             {
                 xmlDocument.Load(A_0);
                 SignedXml signedXml = new SignedXml(xmlDocument);
                 XmlNode xmlNode = xmlDocument.GetElementsByTagName(eval_bw.a(), "http://www.w3.org/2000/09/xmldsig#")[0];
                 signedXml.LoadXml((XmlElement)xmlNode);
                 int num = 7;
                 while (true)
                 {
                     string text2;
                     XmlNode xmlNode2;
                     int num2;
                     TimeSpan timeSpan;
                     switch (num)
                     {
                     case 0:
                         text2 = eval_bw.eval_a(A_1);
                         xmlNode2 = xmlDocument.GetElementsByTagName(text2)[0];
                         num = 9;
                         continue;
                     case 1:
                         goto IL_162;
                     case 2:
                         goto IL_167;
                     case 3:
                         if (num2 > 0)
                         {
                             num = 4;
                             continue;
                         }
                         goto IL_1E6;
                     case 4:
                         result = true;
                         num = 1;
                         continue;
                     case 5:
                         if (A_1 == 0)
                         {
                             num = 2;
                             continue;
                         }
                         goto IL_1E6;
                     case 6:
                         if (timeSpan.Hours > 22)
                         {
                             num = 10;
                             continue;
                         }
                         goto IL_E4;
                     case 7:
                         if (signedXml.CheckSignature(global::eval_s.bc))
                         {
                             num = 0;
                             continue;
                         }
                         goto IL_1E6;
                     case 8:
                         goto IL_E4;
                     case 9:
                         if (A_1 != 2)
                         {
                             num = 11;
                             continue;
                         }
                         goto IL_167;
                     case 10:
                         num2++;
                         num = 8;
                         continue;
                     case 11:
                         num = 5;
                         continue;
                     case 12:
                         goto IL_1F2;
                     }
                     break;
                     IL_E4:
                     num = 3;
                     continue;
                     IL_167:
                     text = text2 + " " + xmlNode2.InnerText;
                     DateTime d = DateTime.Parse(text);
                     DateTime now = DateTime.Now;
                     timeSpan = d - now;
                     num2 = timeSpan.Days;
                     num = 6;
                     continue;
                     IL_1E6:
                     num = 12;
                 }
             }
             IL_162:
             return result;
             IL_1F2:
             goto IL_35;
         }
         catch
         {
             goto IL_35;
         }
         return result;
         IL_35:
         MessageBox.Show(A_0 + " " + text);
         File.Delete(A_0);
         return false;
     }
     }
     goto IL_16;
 }
Пример #37
0
    // Verify the signature of an XML file against an asymetric 
    // algorithm and return the result.
    public static Boolean VerifyXmlFile(String Name, RSA Key)
    {
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Load the passed XML file into the document. 
        xmlDocument.Load(Name);

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDocument);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature(Key);
    }
Пример #38
0
	static void Symmetric (string filename, byte[] key) 
	{
		string shortName = Path.GetFileName (filename);

		XmlDocument doc = new XmlDocument ();
		doc.PreserveWhitespace = true;
		XmlTextReader xtr = new XmlTextReader (GetReader (filename));
		XmlValidatingReader xvr = new XmlValidatingReader (xtr);
		xtr.Normalization = true;
		doc.Load (xvr);
                
		try {
			XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", SignedXml.XmlDsigNamespaceUrl);
			XmlElement signature = (XmlElement) nodeList [0];

			SignedXml s = new SignedXml ();
			s.LoadXml (signature);

			HMACSHA1 mac = new HMACSHA1 (key);
			if (s.CheckSignature (mac)) {
				Console.WriteLine ("valid {0}", shortName);
				valid++;
			}
			else {
				Console.WriteLine ("INVALID {0}", shortName);
				invalid++;
			}
		}
		catch (Exception ex) {
			Console.WriteLine ("EXCEPTION " + shortName + " " + ex);
			error++;
		}
	}