Esempio n. 1
0
        /// <remarks>Sólo se implementan las transformadas de canonicalización</remarks>

        private Stream SignedInfoTransformed()
        {
            System.Security.Cryptography.Xml.Transform t = null;
            switch (signature.SignedInfo.CanonicalizationMethod)
            {
            case XmlSignatureConstants.XmlDsigC14NTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigC14NTransform();
                break;

            case XmlSignatureConstants.XmlDsigC14NWithCommentsTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform();
                break;

            case XmlSignatureConstants.XmlDsigExcC14NTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigExcC14NTransform(signature.SignedInfo.InclusiveNamespaces);
                break;

            case XmlSignatureConstants.XmlDsigExcC14NWithCommentsTransformUrl:
                t = new System.Security.Cryptography.Xml.XmlDsigExcC14NWithCommentsTransform();
                break;

            default:
                t = null;
                break;
            }
            if (t == null)
            {
                return(null);
            }

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;

            XmlElement signatureNode = (XmlElement)envdoc.SelectSingleNode("//*[@Id='" + signature.Id + "']");

            if (signatureNode != null)
            {
                XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(envdoc.NameTable);
                xmlnsManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                XmlNode signedInfoNode = signatureNode.SelectSingleNode("ds:SignedInfo", xmlnsManager);

                doc.LoadXml(signedInfoNode.OuterXml);
            }
            else
            {
                doc.LoadXml(signature.SignedInfo.GetXml().OuterXml);
            }

            var namespaces = GetAllNamespaces(signatureNode);

            foreach (var item in namespaces)
            {
                AddNameSpace(doc, doc.DocumentElement, item.Name, item.Value);
            }

            return(ApplyTransform(t, doc));
        }
Esempio n. 2
0
		string C14N (string xml)
		{
			XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform ();
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (xml);
			t.LoadInput (doc);
			return new StreamReader (t.GetOutput () as Stream).ReadToEnd ();
		}
Esempio n. 3
0
        /// <summary>
        ///     Выполнить каноникализацию XML-узла
        /// </summary>
        /// <param name="node">
        ///     Узел
        /// </param>
        /// <returns>
        ///     Каноникализированный XM-текст
        /// </returns>
        public static string Canonicalize(this XmlNode node)
        {
            var transform = new XmlDsigExcC14NTransform();
            var document = new XmlDocument();

            document.LoadXml(node.OuterXml);
            transform.LoadInput(document);

            using (var stream = (Stream) transform.GetOutput())
            using (var reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
Esempio n. 4
0
        public static XmlDocument SignDocument(XmlDocument doc)
        {
            ////////////////
            string signatureCanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
            string signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            string digestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256";

            string signatureReferenceURI = "#_73e63a41-156d-4fda-a26c-8d79dcade713";

            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), signatureMethod);

            X509Certificate2 signingCertificate = GetCertificate();
            //
            /* add the following lines of code after var signingCertificate = GetCertificate();*/
            CspParameters cspParams = new CspParameters(24);
            //cspParams.KeyContainerName = "XML_DISG_RSA_KEY";
            RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParams);
            var strKey = signingCertificate.PrivateKey.ToXmlString(true);
            key.FromXmlString(strKey);
            /*assign the new key to signer's SigningKey */
            //metadataSigner.SigningKey = key;

            //
            SignedXml signer = new SignedXml(doc);
            signer.SigningKey = key;//signingCertificate.PrivateKey;
            signer.KeyInfo = new KeyInfo();
            signer.KeyInfo.AddClause(new KeyInfoX509Data(signingCertificate));

            signer.SignedInfo.CanonicalizationMethod = signatureCanonicalizationMethod;
            signer.SignedInfo.SignatureMethod = signatureMethod;

            XmlDsigEnvelopedSignatureTransform envelopeTransform = new XmlDsigEnvelopedSignatureTransform();
            XmlDsigExcC14NTransform cn14Transform = new XmlDsigExcC14NTransform();

            Reference signatureReference = new Reference("#FATCA");
            signatureReference.Uri = signatureReferenceURI;
            signatureReference.AddTransform(envelopeTransform);
            signatureReference.AddTransform(cn14Transform);
            signatureReference.DigestMethod = digestMethod;

            signer.AddReference(signatureReference);

            signer.ComputeSignature();
            XmlElement signatureElement = signer.GetXml();

            doc.DocumentElement.AppendChild(signer.GetXml());

            return doc;
        }
Esempio n. 5
0
        private SignatureVerificationResult VerifyAuthenticodeExpectedHash(XmlElement licenseNode)
        {
            XmlElement element = licenseNode.SelectSingleNode("r:grant/as:ManifestInformation", this.m_namespaceManager) as XmlElement;

            if (element == null)
            {
                return(SignatureVerificationResult.BadSignatureFormat);
            }
            string attribute = element.GetAttribute("Hash");

            if (string.IsNullOrEmpty(attribute))
            {
                return(SignatureVerificationResult.BadSignatureFormat);
            }
            byte[]      lhs      = BackwardHexToBytes(attribute);
            XmlDocument document = new XmlDocument {
                PreserveWhitespace = true
            };
            XmlReaderSettings settings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Parse
            };

            using (TextReader reader = new StringReader(this.m_manifestXml.OuterXml))
            {
                using (XmlReader reader2 = XmlReader.Create(reader, settings, this.m_manifestXml.BaseURI))
                {
                    document.Load(reader2);
                }
            }
            XmlElement oldChild = document.SelectSingleNode("//asm:assembly/ds:Signature", this.m_namespaceManager) as XmlElement;

            oldChild.ParentNode.RemoveChild(oldChild);
            XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform();

            transform.LoadInput(document);
            byte[] rhs = null;
            using (SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider())
            {
                rhs = provider.ComputeHash(transform.GetOutput() as MemoryStream);
            }
            if (!CompareBytes(lhs, rhs))
            {
                return(SignatureVerificationResult.BadDigest);
            }
            return(SignatureVerificationResult.Valid);
        }
Esempio n. 6
0
        private Transform GetC14NMethod()
        {
            Transform t = null;

            if (m_signature.SignedInfo.CanonicalizationMethod.Contains("http://www.w3.org/2001/10/xml-exc-c14n#"))
            {
                t = new XmlDsigExcC14NTransform();
            }

            if (t == null)
            {
                t = (Transform)CryptoConfig.CreateFromName(m_signature.SignedInfo.CanonicalizationMethod);
            }
            if (t == null)
            {
                throw new CryptographicException("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
            }
            return(t);
        }
Esempio n. 7
0
        public static void SignXmlSoap(
            this Message message,
            X509Certificate2 certificate)
        {
            XmlDocument signedMessageXml = message.Xml;

            SmevSignedXml signedXml = new SmevSignedXml(signedMessageXml);

            signedXml.SigningKey = certificate.PrivateKey;

            Reference reference = new Reference();
            reference.Uri = "#body";

            reference.DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete;

            XmlDsigExcC14NTransform c14 = new XmlDsigExcC14NTransform();
            reference.AddTransform(c14);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            signedXml.SignedInfo.SignatureMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3410UrlObsolete;
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            string xmldsig = @"http://www.w3.org/2000/09/xmldsig#";
            string wsse = @"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";

            var namespaceManager = new XmlNamespaceManager(new NameTable());
            namespaceManager.AddNamespace("ds", xmldsig);
            namespaceManager.AddNamespace("wsse", wsse);

            signedMessageXml.GetElementsByTagName("Signature", xmldsig)[0].PrependChild(
                signedMessageXml.ImportNode(xmlDigitalSignature.GetElementsByTagName("SignatureValue", xmldsig)[0], true)
            );
            signedMessageXml.GetElementsByTagName("Signature", xmldsig)[0].PrependChild(
                signedMessageXml.ImportNode(xmlDigitalSignature.GetElementsByTagName("SignedInfo", xmldsig)[0], true)
            );

            signedMessageXml.GetElementsByTagName("BinarySecurityToken", wsse)[0].InnerText = Convert.ToBase64String(certificate.RawData);
        }
Esempio n. 8
0
        public static void SignSingleEntity(
            this GisGmp.Message message,
            X509Certificate2 certificate,
            XmlNode entityXml)
        {
            XmlDocument signingDoc = new XmlDocument();
            signingDoc.LoadXml(entityXml.OuterXml);

            SmevSignedXml signedXml = new SmevSignedXml(signingDoc);
            signedXml.SigningKey = certificate.PrivateKey;

            Reference reference = new Reference();
            reference.Uri = "";
            reference.DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete;

            XmlDsigEnvelopedSignatureTransform envelopedSignature = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(envelopedSignature);
            XmlDsigExcC14NTransform c14 = new XmlDsigExcC14NTransform();
            reference.AddTransform(c14);

            KeyInfo ki = new KeyInfo();
            ki.AddClause(new KeyInfoX509Data(certificate));

            signedXml.KeyInfo = ki;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3410UrlObsolete;
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            signingDoc.DocumentElement.AppendChild(xmlDigitalSignature);

            XmlDocumentFragment signedFinalPayment = message.Xml.CreateDocumentFragment();
            signedFinalPayment.InnerXml = signingDoc.OuterXml;

            var documentNode = entityXml.ParentNode;
            documentNode.RemoveChild(entityXml);
            documentNode.AppendChild(signedFinalPayment);
        }
        /// <summary>
        /// Signs an XML Document for a Saml Response
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="cert2"></param>
        /// <param name="referenceId"></param>
        /// <returns></returns>
        public static XmlElement SignDoc(XmlDocument doc, X509Certificate2 cert2, string referenceId, string referenceValue)
        {
            SamlSignedXml sig = new SamlSignedXml(doc, referenceId);
            // Add the key to the SignedXml xmlDocument.
            sig.SigningKey = cert2.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = String.Empty;
            // reference.Uri = "#" + referenceValue;

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new
                XmlDsigEnvelopedSignatureTransform();
            XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform();

            reference.AddTransform(env);
            reference.AddTransform(env2);

            // Add the reference to the SignedXml object.
            sig.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyData = new KeyInfoX509Data(cert2);

            keyInfo.AddClause(keyData);

            sig.KeyInfo = keyInfo;

            // Compute the signature.
            sig.ComputeSignature();

            // Get the XML representation of the signature and save it to an XmlElement object.
            XmlElement xmlDigitalSignature = sig.GetXml();

            return xmlDigitalSignature;
        }
        private static XmlDocument SignSmevRequest(XmlDocument smevRequest, X509Certificate2 signingCertificate)
        {
            // Создание подписчика XML-документа
            var signedXml = new GostSignedXml(smevRequest) { GetIdElementHandler = GetSmevIdElement };

            // Установка ключа для создания подписи
            signedXml.SetSigningCertificate(signingCertificate);

            // Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования ГОСТ Р 34.11-94 (в соответствии с методическими рекомендациями СМЭВ)
            var dataReference = new Reference { Uri = "#body", DigestMethod = GostSignedXml.XmlDsigGost3411ObsoleteUrl };

            // Метод преобразования, применяемый к данным перед их подписью (в соответствии с методическими рекомендациями СМЭВ)
            var dataTransform = new XmlDsigExcC14NTransform();
            dataReference.AddTransform(dataTransform);

            // Установка ссылки на узел
            signedXml.AddReference(dataReference);

            // Установка алгоритма нормализации узла SignedInfo (в соответствии с методическими рекомендациями СМЭВ)
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Установка алгоритма подписи ГОСТ Р 34.10-2001 (в соответствии с методическими рекомендациями СМЭВ)
            signedXml.SignedInfo.SignatureMethod = GostSignedXml.XmlDsigGost3410ObsoleteUrl;

            // Вычисление подписи
            signedXml.ComputeSignature();

            // Получение XML-представления подписи
            var signatureXml = signedXml.GetXml();

            // Добавление подписи в исходный документ
            smevRequest.GetElementsByTagName("ds:Signature")[0].PrependChild(smevRequest.ImportNode(signatureXml.GetElementsByTagName("SignatureValue")[0], true));
            smevRequest.GetElementsByTagName("ds:Signature")[0].PrependChild(smevRequest.ImportNode(signatureXml.GetElementsByTagName("SignedInfo")[0], true));
            smevRequest.GetElementsByTagName("wsse:BinarySecurityToken")[0].InnerText = Convert.ToBase64String(signingCertificate.RawData);

            return smevRequest;
        }
		void CheckProperties (XmlDsigExcC14NTransform transform)
		{
			Type[] input = transform.InputTypes;
			Assert.IsTrue ((input.Length == 3), "Input #");
			// check presence of every supported input types
			bool istream = false;
			bool ixmldoc = false;
			bool ixmlnl = false;
			foreach (Type t in input) {
				if (t.ToString () == "System.IO.Stream")
					istream = true;
				if (t.ToString () == "System.Xml.XmlDocument")
					ixmldoc = true;
				if (t.ToString () == "System.Xml.XmlNodeList")
					ixmlnl = true;
			}
			Assert.IsTrue (istream, "Input Stream");
			Assert.IsTrue (ixmldoc, "Input XmlDocument");
			Assert.IsTrue (ixmlnl, "Input XmlNodeList");

			Type[] output = transform.OutputTypes;
			Assert.IsTrue ((output.Length == 1), "Output #");
			// check presence of every supported output types
			bool ostream = false;
			foreach (Type t in output) {
				if (t.ToString () == "System.IO.Stream")
					ostream = true;
			}
			Assert.IsTrue (ostream, "Output Stream");
		}
Esempio n. 12
0
		private void addReferenceButton_Click(object sender, System.EventArgs e)
		{
			XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform;
			Reference reference;
			
			reference = new Reference();

            reference.DigestMethod = "http://www.w3.org/2001/04/xmldsig-more#gostr3411";

			if (this.envelopedSignatureRadioButton.Checked)
			{
				if (this.newSignatureCheckBox.Checked)
				{
					this.envelopedSignatureXmlDocument = new XmlDocument();
					this.documentDataObjectCounter = 1;
				}
				this.envelopedSignatureXmlDocument.PreserveWhitespace = true;
				this.envelopedSignatureXmlDocument.Load(this.envelopingDocumentTextBox.Text);
				this.xadesSignedXml = new XadesSignedXml(this.envelopedSignatureXmlDocument);

				reference.Uri = "";
                XmlDsigExcC14NTransform xmlDsigC14NTransform = new XmlDsigExcC14NTransform();
				reference.AddTransform(xmlDsigC14NTransform);
				xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
				reference.AddTransform(xmlDsigEnvelopedSignatureTransform);
			}
			else
			{
				if (this.newSignatureCheckBox.Checked)
				{
					this.xadesSignedXml = new XadesSignedXml();
					this.documentDataObjectCounter = 1;
				}
				if (this.includedXmlRadioButton.Checked)
				{
					reference.Uri = "#" + this.objectIdPrefixTextBox.Text + this.documentDataObjectCounter.ToString();
					reference.Type = SignedXml.XmlDsigNamespaceUrl + "Object";

					//Add an object
					System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject();
					XmlDocument xmlDocument = new XmlDocument();
					xmlDocument.PreserveWhitespace = true;
					xmlDocument.LoadXml(this.includedXmltextBox.Text);
					dataObject.Data = xmlDocument.ChildNodes;
					dataObject.Id = this.objectIdPrefixTextBox.Text + this.documentDataObjectCounter.ToString();
					this.xadesSignedXml.AddObject(dataObject);
				}
				else
				{
					reference.Uri = this.externalDocumentUrlTextBox.Text;
					if (reference.Uri.EndsWith(".xml") || reference.Uri.EndsWith(".XML")) 
					{
						reference.AddTransform(new XmlDsigC14NTransform());
					}
				}
			}
			this.xadesSignedXml.AddReference(reference);
			this.documentDataObjectCounter++;
			this.nextObjectIdSuffixLabel.Text = this.documentDataObjectCounter.ToString();
		}
Esempio n. 13
0
        private static void SignXmlSec1(EnvConfig envConfig, string templateName, string outputName, AppId appId)
        {
            Program.LogAction("signing with xmlsec1: [{0}] => [{1}]", templateName, outputName);

            // load manifest input xml
            var docTemplate = new XmlDocument();
            docTemplate.Load(templateName);
            var nsmgr = CreateDefaultXmlNsmgr(docTemplate);

            // insert publisher identity
            var pfx = UnlockPfx(File.ReadAllBytes(envConfig.ClickOnce.KeyFile));
            var cert = pfx.Certificates.Cast<X509Certificate>().Single();
            var publisherName = cert.SubjectName;
            // as described on http://msdn.microsoft.com/en-us/library/dd996956.aspx
            var issuerKeyHash = FormatKey(_sha1.ComputeHash(cert.PublicKey));

            var publisherIdentity = docTemplate.CreateElement("publisherIdentity", ASMv2_NS);
            SetOrReplaceAttribute(publisherIdentity, "name", null, publisherName);
            SetOrReplaceAttribute(publisherIdentity, "issuerKeyHash", null, issuerKeyHash);

            docTemplate.ChildNodes.OfType<XmlElement>().Last().AppendChild(publisherIdentity);

            var fusionTemplateName = templateName + ".fusion";
            docTemplate.Save(fusionTemplateName);

            //
            // Calculate ManifestInformation Hash
            // ==================================
            // The Fusion XML engine is always preserving whitespace, therefore we need to
            // use a specially configured XmlDocument to normalize and sign the Manifest.
            //
            byte[] hash;
            {
                var fusionDoc = new XmlDocument();
                fusionDoc.PreserveWhitespace = true;
                fusionDoc.Load(fusionTemplateName);

                var transform = new XmlDsigExcC14NTransform();
                transform.LoadInput(fusionDoc);
                hash = _sha1.ComputeHash((MemoryStream)transform.GetOutput());
            }

            // Load SignatureBlock into DOM
            var signatureTemplate = LoadXmlFromResource("PrepareEnv.Templates.SignatureBlock.xml");
            foreach (XmlNode sigNode in signatureTemplate.DocumentElement.ChildNodes)
            {
                var newChild = docTemplate.ImportNode(sigNode, deep: true);
                docTemplate.DocumentElement.AppendChild(newChild);
                foreach (XmlNode assemblyId in newChild.SelectNodes("//as:assemblyIdentity", nsmgr))
                {
                    // authenticode assemblyIdentity looks like asmv1:assemblyIdentity
                    FillAppId(envConfig, assemblyId, appId);
                }
            }

            // Set ManifestInformation Hash
            var manifestInfo = docTemplate.SelectSingleNode("//as:ManifestInformation", nsmgr);
            SetOrReplaceAttribute(manifestInfo, "Hash", null, FormatKey(hash));

            // Set AuthenticodePublisher's SubjectName
            var subjectName = docTemplate.SelectSingleNode("//as:AuthenticodePublisher/as:X509SubjectName", nsmgr);
            subjectName.InnerText = publisherName;

            // Sign everything
            Program.LogDetail("saving to xmlsec1 template: [{0}]", templateName + ".xmlsec1");
            docTemplate.Save(templateName + ".xmlsec1");

            var pw = _passphrase == null ? string.Empty : string.Format("--pwd \"{0}\"", _passphrase);

            // resign manifest RelData
            var relDataArgs = string.Format("--sign {0} {1} {2} --node-xpath \"//*[local-name()='RelData']\" --enabled-key-data rsa,x509 --output \"{3}.reldata\" \"{4}.xmlsec1\"",
                                            pw,
                                            envConfig.ClickOnce.KeyFile.EndsWith("pfx") ? "--pkcs12" : "--privkey-pem",
                                            envConfig.ClickOnce.KeyFile,
                                            outputName,
                                            templateName);
            Program.LogDetail("signing reldata to [{0}.reldata]", outputName);
            var proc = Process.Start(new ProcessStartInfo("xmlsec1", relDataArgs) { UseShellExecute = false });
            proc.WaitForExit();
            if (proc.ExitCode != 0)
            {
                throw new InvalidOperationException(string.Format("xmlsec1 complained about {0}", relDataArgs));
            }

            // resign complete manifest
            var finalArgs = string.Format("--sign {0} {1} {2} --enabled-key-data rsa,x509 --output \"{3}\" \"{3}.reldata\"",
                                          pw,
                                          envConfig.ClickOnce.KeyFile.EndsWith("pfx") ? "--pkcs12" : "--privkey-pem",
                                          envConfig.ClickOnce.KeyFile,
                                          outputName);
            Program.LogDetail("signing final to : [{0}]", outputName);
            proc = Process.Start(new ProcessStartInfo("xmlsec1", finalArgs) { UseShellExecute = false });
            proc.WaitForExit();
            if (proc.ExitCode != 0)
            {
                throw new InvalidOperationException(string.Format("xmlsec1 complained about {0}", finalArgs));
            }
        }
		void AppendNegotiationMessageXml (XmlReader reader, TlsServerSessionInfo tlsInfo)
		{
			XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform ();
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			reader.MoveToContent ();
			doc.AppendChild (doc.ReadNode (reader));
			t.LoadInput (doc);
			MemoryStream stream = (MemoryStream) t.GetOutput ();
			byte [] bytes = stream.ToArray ();
			tlsInfo.Messages.Write (bytes, 0, bytes.Length);
		}
Esempio n. 15
0
        public static void Sign(XmlDocument doc)
        {
            string signatureCanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
            string signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            string digestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256";

            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), signatureMethod);

            X509Certificate2 signingCertificate = GetCertificate();

            SignedXml signer = new SignedXml(doc);

            CspParameters cspParams = new CspParameters(24);
            cspParams.KeyContainerName = "XML_DISG_RSA_KEY";

            RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParams);
            var strKey = signingCertificate.PrivateKey.ToXmlString(true);
            key.FromXmlString(strKey);

            signer.SigningKey = key;
            signer.KeyInfo = new KeyInfo();
            var x509Data = new KeyInfoX509Data(signingCertificate);
            //SubjectName
            var dname = new X500DistinguishedName(signingCertificate.SubjectName);
            Console.WriteLine("X500DistinguishedName: {0}{1}", dname.Name, Environment.NewLine);
            x509Data.AddSubjectName(dname.Name);
            signer.KeyInfo.AddClause(x509Data);

            signer.SignedInfo.CanonicalizationMethod = signatureCanonicalizationMethod;
            signer.SignedInfo.SignatureMethod = signatureMethod;

            //XmlDsigEnvelopedSignatureTransform envelopeTransform = new XmlDsigEnvelopedSignatureTransform();
            Transform cn14Transform = new XmlDsigExcC14NTransform();
            //Transform cn14Transform = new XmlDsigC14NTransform();

            Reference signatureReference = new Reference("#FATCA");
            //signatureReference.Uri = signatureReferenceURI;
            //signatureReference.AddTransform(envelopeTransform);
            signatureReference.AddTransform(cn14Transform);
            signatureReference.DigestMethod = digestMethod;

            signer.AddReference(signatureReference);
            //signer.AddReference(new Reference("#tag1"));
            //signer.AddReference(new Reference("#tag3"));

            signer.ComputeSignature();

            XmlElement signatureElement = signer.GetXml();
            Console.WriteLine(signatureElement.NamespaceURI);
            String strDoc = signatureElement.OuterXml;
            XmlDocument docResult = new XmlDocument();
            docResult.LoadXml(strDoc);
            Console.WriteLine(signatureElement.NamespaceURI);
            //XmlElement obj = docResult.CreateElement("Object",docResult.FirstChild.NamespaceURI);
            //obj.SetAttribute("Id", "FACTA");

            var xfrag = docResult.CreateDocumentFragment();

            xfrag.InnerXml = doc.OuterXml;
            //xfrag.FirstChild.Attributes.Append(xfrag.C.CreateAttribute("xx")).Value = docResult.NamespaceURI;

            //obj.AppendChild(xfrag);
            //docResult.DocumentElement.AppendChild(obj);
            if (docResult.DocumentElement == null)
                throw new Exception("docResult.DocumentElement no puede ser NULL");
            var node = docResult.DocumentElement.AppendChild(xfrag);
            //node.FirstChild.Attributes.Append(doc.CreateAttribute("xx")).Value = docResult.NamespaceURI;

            //doc.DocumentElement.AppendChild(signer.GetXml());

            var settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = false;
            settings.Indent = true;

            var writer = XmlWriter.Create("output1.xml", settings);
            docResult.Save(writer);
            //docResult.Save("output.xml");

            Console.WriteLine("Namespace:{0}",docResult.FirstChild.NamespaceURI);
            //Console.ReadLine();
        }
Esempio n. 16
0
        public byte[] ComputeHashValueOfElementList(XmlElement signatureXmlElement, ArrayList elementXpaths)
        {
            XmlDocument xmlDocument;
            XmlNamespaceManager xmlNamespaceManager;
            XmlNodeList searchXmlNodeList;
            XmlElement composedXmlElement;
            XmlDsigExcC14NTransform xmlTransform;

            Stream canonicalizedStream;
            //SHA1 sha1Managed;
            byte[] retVal;

            xmlDocument = signatureXmlElement.OwnerDocument;
            composedXmlElement = xmlDocument.CreateElement("ComposedElement", SignedXml.XmlDsigNamespaceUrl);
            xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
            xmlNamespaceManager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            xmlNamespaceManager.AddNamespace("xsd", XadesSignedXml.XadesNamespaceUri);
            foreach (string elementXpath in elementXpaths)
            {
                searchXmlNodeList = signatureXmlElement.SelectNodes(elementXpath, xmlNamespaceManager);
                if (searchXmlNodeList.Count == 0)
                {
                    throw new CryptographicException("Element " + elementXpath + " not found while calculating hash");
                }
                foreach (XmlNode xmlNode in searchXmlNodeList)
                {
                    //jbonilla Id attr deprecated
                    //if (((XmlElement)xmlNode).HasAttribute("Id"))
                    //{
                    //    elementIdValues.Add(((XmlElement)xmlNode).Attributes["Id"].Value);
                    //    composedXmlElement.AppendChild(xmlNode);
                    //}
                    //else
                    //{
                    //    throw new CryptographicException("Id attribute missing on " + xmlNode.LocalName + " element");
                    //}
                    composedXmlElement.AppendChild(xmlNode);
                }
            }

            //Initialise the stream to read the node list
            MemoryStream nodeStream = new MemoryStream();
            XmlWriter xw = XmlWriter.Create(nodeStream);
            composedXmlElement.ChildNodes[0].WriteTo(xw);
            xw.Flush();
            nodeStream.Position = 0;

            //modificado
            xmlTransform = new XmlDsigExcC14NTransform();
            xmlTransform.LoadInput(nodeStream);

            canonicalizedStream = (Stream)xmlTransform.GetOutput(typeof(Stream));

            //sha1Managed = new SHA1Managed();
            //retVal = sha1Managed.ComputeHash(canonicalizedStream);
            IDigest digest = this.tspSource.GetMessageDigest();
            byte[] canonicalizedBytes = Streams.ReadAll(canonicalizedStream);
            digest.BlockUpdate(canonicalizedBytes, 0, canonicalizedBytes.Length);
            retVal = DigestUtilities.DoFinal(digest);

            canonicalizedStream.Close();

            return retVal;
        }
Esempio n. 17
0
        private static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldFormat)
        {
            if (oldFormat)
            {
                XmlDsigExcC14NTransform exc = new XmlDsigExcC14NTransform();
                exc.LoadInput(manifestDom);
                using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
                {
                    byte[] hash = sha1.ComputeHash(exc.GetOutput() as MemoryStream);
                    if (hash == null)
                    {
                        throw new CryptographicException(Win32.TRUST_E_BAD_DIGEST);
                    }

                    return hash;
                }
            }
            else
            {
                // Since the DOM given to us is not guaranteed to be normalized,
                // we need to normalize it ourselves. Also, we always preserve
                // white space as Fusion XML engine always preserve white space.
                XmlDocument normalizedDom = new XmlDocument();
                normalizedDom.PreserveWhitespace = true;

                // Normalize the document
                using (TextReader stringReader = new StringReader(manifestDom.OuterXml))
                {
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.DtdProcessing = DtdProcessing.Parse;
                    XmlReader reader = XmlReader.Create(stringReader, settings, manifestDom.BaseURI);
                    normalizedDom.Load(reader);
                }

                XmlDsigExcC14NTransform exc = new XmlDsigExcC14NTransform();
                exc.LoadInput(normalizedDom);
                using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
                {
                    byte[] hash = sha1.ComputeHash(exc.GetOutput() as MemoryStream);
                    if (hash == null)
                    {
                        throw new CryptographicException(Win32.TRUST_E_BAD_DIGEST);
                    }

                    return hash;
                }
            }
        }
Esempio n. 18
0
		private Transform GetC14NMethod ()
		{
			Transform t = null;
			if (m_signature.SignedInfo.CanonicalizationMethod.Contains ("http://www.w3.org/2001/10/xml-exc-c14n#")) {
				t = new XmlDsigExcC14NTransform ();
			}

			if (t == null)
				t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
			if (t == null)
				throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
			return t;
		}
Esempio n. 19
0
		public void LoadXml (XmlElement value) 
		{
			if (value == null)
				throw new ArgumentNullException ("value");

			if ((value.LocalName != XmlSignature.ElementNames.Reference) || (value.NamespaceURI != XmlSignature.NamespaceURI))
				throw new CryptographicException ();

			id = GetAttribute (value, XmlSignature.AttributeNames.Id);
			uri = GetAttribute (value, XmlSignature.AttributeNames.URI);
			type = GetAttribute (value, XmlSignature.AttributeNames.Type);
			// Note: order is important for validations
			XmlNodeList xnl = value.GetElementsByTagName (XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI);
			if ((xnl != null) && (xnl.Count > 0)) {
				Transform t = null;
				foreach (XmlNode xn in xnl) {
					string a = GetAttribute ((XmlElement)xn, XmlSignature.AttributeNames.Algorithm);
/*	This code is useful for debugging in VS.NET because using CryptoConfig
	(from MS mscorlib) would throw InvalidCastException because it's 
	Transform would come from MS System.Security.dll not Mono's.*/
					switch (a) {
						case "http://www.w3.org/2000/09/xmldsig#base64":
							t = new XmlDsigBase64Transform ();
							break;
						case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
							t = new XmlDsigC14NTransform ();
							break;
						case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
							t = new XmlDsigC14NWithCommentsTransform ();
							break;
						case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
							t = new XmlDsigEnvelopedSignatureTransform ();
							break;
						case "http://www.w3.org/TR/1999/REC-xpath-19991116":
							t = new XmlDsigXPathTransform ();
							break;
						case "http://www.w3.org/TR/1999/REC-xslt-19991116":
							t = new XmlDsigXsltTransform ();
							break;
						case "http://www.w3.org/2002/07/decrypt#XML":
							t = new XmlDecryptionTransform ();
							break;
						case "http://www.w3.org/2001/10/xml-exc-c14n#":
							t = new XmlDsigExcC14NTransform ();
							break;
						default:
							throw new NotSupportedException ();
					}

					if (t == null)
						t = (Transform) CryptoConfig.CreateFromName (a);
					if (t == null)
						throw new CryptographicException ("Unknown transform {0}.", a);

					if (xn.ChildNodes.Count > 0) {
						t.LoadInnerXml (xn.ChildNodes);
					}
					AddTransform (t);
				}
			}
			// get DigestMethod
			DigestMethod = XmlSignature.GetAttributeFromElement (value, XmlSignature.AttributeNames.Algorithm, XmlSignature.ElementNames.DigestMethod);
			// get DigestValue
			XmlElement dig = XmlSignature.GetChildElement (value, XmlSignature.ElementNames.DigestValue, XmlSignature.NamespaceURI);
			if (dig != null)
				DigestValue = Convert.FromBase64String (dig.InnerText);
			element = value;
		}
 private SignatureVerificationResult VerifyAuthenticodeExpectedHash(XmlElement licenseNode)
 {
     XmlElement element = licenseNode.SelectSingleNode("r:grant/as:ManifestInformation", this.m_namespaceManager) as XmlElement;
     if (element == null)
     {
         return SignatureVerificationResult.BadSignatureFormat;
     }
     string attribute = element.GetAttribute("Hash");
     if (string.IsNullOrEmpty(attribute))
     {
         return SignatureVerificationResult.BadSignatureFormat;
     }
     byte[] lhs = BackwardHexToBytes(attribute);
     XmlDocument document = new XmlDocument {
         PreserveWhitespace = true
     };
     XmlReaderSettings settings = new XmlReaderSettings {
         DtdProcessing = DtdProcessing.Parse
     };
     using (TextReader reader = new StringReader(this.m_manifestXml.OuterXml))
     {
         using (XmlReader reader2 = XmlReader.Create(reader, settings, this.m_manifestXml.BaseURI))
         {
             document.Load(reader2);
         }
     }
     XmlElement oldChild = document.SelectSingleNode("//asm:assembly/ds:Signature", this.m_namespaceManager) as XmlElement;
     oldChild.ParentNode.RemoveChild(oldChild);
     XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform();
     transform.LoadInput(document);
     byte[] rhs = null;
     using (SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider())
     {
         rhs = provider.ComputeHash(transform.GetOutput() as MemoryStream);
     }
     if (!CompareBytes(lhs, rhs))
     {
         return SignatureVerificationResult.BadDigest;
     }
     return SignatureVerificationResult.Valid;
 }
Esempio n. 21
0
		public virtual void LoadXml (XmlElement value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
			else {
				Uri = null;
				TransformChain = new TransformChain ();

				foreach (XmlNode n in value.ChildNodes) {
					if (n is XmlWhitespace)
						continue;

					switch (n.LocalName) {
					case XmlEncryption.ElementNames.Transforms:
						foreach (XmlNode xn in ((XmlElement) n).GetElementsByTagName (XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI)) {
							Transform t = null;
							switch (((XmlElement) xn).Attributes [XmlSignature.AttributeNames.Algorithm].Value) {
							case XmlSignature.AlgorithmNamespaces.XmlDsigBase64Transform:
								t = new XmlDsigBase64Transform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NTransform:
								t = new XmlDsigC14NTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigC14NWithCommentsTransform:
								t = new XmlDsigC14NWithCommentsTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigEnvelopedSignatureTransform:
								t = new XmlDsigEnvelopedSignatureTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXPathTransform:
								t = new XmlDsigXPathTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigXsltTransform:
								t = new XmlDsigXsltTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NTransform:
								t = new XmlDsigExcC14NTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NWithCommentsTransform:
								t = new XmlDsigExcC14NWithCommentsTransform ();
								break;
							case XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform:
								t = new XmlDecryptionTransform ();
								break;
							default:
								continue;
							}

							t.LoadInnerXml (((XmlElement) xn).ChildNodes);
							TransformChain.Add (t);
						}
						break;
					}
				}

				if (value.HasAttribute (XmlEncryption.AttributeNames.URI))
					Uri = value.Attributes [XmlEncryption.AttributeNames.URI].Value;
			}
		}
Esempio n. 22
0
        private static void SignDocument(X509Certificate2 cert, XmlDocument doc)
        {
            
            //Create reference to #MsgBody which is the ID of the SOAP Body (only signing the Body)
            Reference reference = new Reference("#MsgBody");

            //Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);


            //Create a signedXML object from doc, add reference and private key, then generate the signature
            SignedXml signedXML = new SignedXml(doc);
            signedXML.AddReference(reference);
            
            RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)cert.PrivateKey;
            signedXML.SigningKey = rsaKey;

            // Changes done to support SHA2 - START ===================
            var cn14Transform = new XmlDsigExcC14NTransform();

            string referenceDigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
            reference.AddTransform(cn14Transform);
            reference.DigestMethod = referenceDigestMethod;
            signedXML.AddReference(reference);

            KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create("RSA-SHA256");
            // Changes done to support SHA2 - END ===================
            
            // Compute the signature.
            signedXML.ComputeSignature();

            // Get the XML representation of the signature and add to the SOAP Header
            XmlElement xmlDigitalSignature = signedXML.GetXml();
            doc.DocumentElement.FirstChild.FirstChild.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

            // Add KeyInfo Node with reference to the X509 cert
            XmlDocument keyInfo = new XmlDocument();
            keyInfo.LoadXml("<root xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" ><ds:KeyInfo><SecurityTokenReference xmlns=\"http://schemas.xmlsoap.org/ws/2002/04/secext\"><wsse:Reference URI=\"#X509Token\"/></SecurityTokenReference></ds:KeyInfo></root>");
            doc.DocumentElement.FirstChild.FirstChild.LastChild.AppendChild(doc.ImportNode(keyInfo.FirstChild.FirstChild, true));

            //Add The Base64 representation of the X509 cert to BinarySecurityToken Node
            //X509SecurityToken token = new X509SecurityToken(cert);
            doc.DocumentElement.FirstChild.LastChild.InnerText = Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.None);

        }
Esempio n. 23
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if ((value.LocalName != XmlSignature.ElementNames.Reference) || (value.NamespaceURI != XmlSignature.NamespaceURI))
            {
                throw new CryptographicException();
            }

            id   = GetAttribute(value, XmlSignature.AttributeNames.Id);
            uri  = GetAttribute(value, XmlSignature.AttributeNames.URI);
            type = GetAttribute(value, XmlSignature.AttributeNames.Type);
            // Note: order is important for validations
            XmlNodeList xnl = value.GetElementsByTagName(XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI);

            if ((xnl != null) && (xnl.Count > 0))
            {
                Transform t = null;
                foreach (XmlNode xn in xnl)
                {
                    string a = GetAttribute((XmlElement)xn, XmlSignature.AttributeNames.Algorithm);

/*	This code is useful for debugging in VS.NET because using CryptoConfig
 *      (from MS mscorlib) would throw InvalidCastException because it's
 *      Transform would come from MS System.Security.dll not Mono's.*/
                    switch (a)
                    {
                    case "http://www.w3.org/2000/09/xmldsig#base64":
                        t = new XmlDsigBase64Transform();
                        break;

                    case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
                        t = new XmlDsigC14NTransform();
                        break;

                    case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
                        t = new XmlDsigC14NWithCommentsTransform();
                        break;

                    case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
                        t = new XmlDsigEnvelopedSignatureTransform();
                        break;

                    case "http://www.w3.org/TR/1999/REC-xpath-19991116":
                        t = new XmlDsigXPathTransform();
                        break;

                    case "http://www.w3.org/TR/1999/REC-xslt-19991116":
                        t = new XmlDsigXsltTransform();
                        break;

                    case "http://www.w3.org/2002/07/decrypt#XML":
                        t = new XmlDecryptionTransform();
                        break;

                    case "http://www.w3.org/2001/10/xml-exc-c14n#":
                        t = new XmlDsigExcC14NTransform();
                        break;

                    default:
                        throw new NotSupportedException();
                    }

                    if (t == null)
                    {
                        t = (Transform)CryptoConfig.CreateFromName(a);
                    }
                    if (t == null)
                    {
                        throw new CryptographicException("Unknown transform {0}.", a);
                    }

                    if (xn.ChildNodes.Count > 0)
                    {
                        t.LoadInnerXml(xn.ChildNodes);
                    }
                    AddTransform(t);
                }
            }
            // get DigestMethod
            DigestMethod = XmlSignature.GetAttributeFromElement(value, XmlSignature.AttributeNames.Algorithm, XmlSignature.ElementNames.DigestMethod);
            // get DigestValue
            XmlElement dig = XmlSignature.GetChildElement(value, XmlSignature.ElementNames.DigestValue, XmlSignature.NamespaceURI);

            if (dig != null)
            {
                DigestValue = Convert.FromBase64String(dig.InnerText);
            }
            element = value;
        }
		public void Types ()
		{
			Type [] input = transform.InputTypes;
			input [0] = null;
			input [1] = null;
			input [2] = null;
			// property does not return a clone
			foreach (Type t in transform.InputTypes) {
				Assert.IsNull (t);
			}
			// it's not a static array
			XmlDsigExcC14NTransform t2 = new XmlDsigExcC14NTransform ();
			foreach (Type t in t2.InputTypes) {
				Assert.IsNotNull (t);
			}
		}
		public void SimpleNamespacePrefixes ()
		{
			string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>";
			string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>";

			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (input);
			XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform ();
			t.LoadInput (doc);
			Stream s = t.GetOutput () as Stream;
			Assert.AreEqual (new StreamReader (s, Encoding.UTF8).ReadToEnd (), expected);
		}
Esempio n. 26
0
        /// <summary>
        /// Signs the document given as an argument.
        /// </summary>
        private static void SignDocument(XmlDocument doc)
        {
            SignedXml signedXml = new SignedXml(doc);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            // TODO Dynamically dig out the correct ID attribute from the XmlDocument.
            Reference reference = new Reference("#_b8977dc86cda41493fba68b32ae9291d"); 
            // Assert.That(reference.Uri == string.Empty);

            XmlDsigEnvelopedSignatureTransform envelope = new XmlDsigEnvelopedSignatureTransform();                        
            reference.AddTransform(envelope);

            // NOTE: C14n may require the following list of namespace prefixes. Seems to work without it, though.
            //List<string> prefixes = new List<string>();
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2000/09/xmldsig#"));
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2001/XMLSchema-instance"));
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2001/XMLSchema"));
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("urn:oasis:names:tc:SAML:2.0:assertion"));

            //XmlDsigExcC14NTransform C14NTransformer = new XmlDsigExcC14NTransform(string.Join(" ", prefixes.ToArray()).Trim());
            XmlDsigExcC14NTransform C14NTransformer = new XmlDsigExcC14NTransform();

            reference.AddTransform(C14NTransformer);            

            signedXml.AddReference(reference);

            // Add the key to the signature, so the assertion can be verified by itself.
            signedXml.KeyInfo = new KeyInfo();

            // Use RSA key for signing.
            //{
            //    CspParameters parameters = new CspParameters();
            //    parameters.KeyContainerName = "XML_DSIG_RSA_KEY";
            //    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(parameters);
            //    signedXml.SigningKey = rsaKey;
            //    signedXml.KeyInfo.AddClause(new RSAKeyValue(rsaKey));
            //}

            // Use X509 Certificate for signing.
            {
                X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234");
                Assert.That(cert.HasPrivateKey);
                signedXml.SigningKey = cert.PrivateKey;
                signedXml.KeyInfo.AddClause(new KeyInfoX509Data(cert,X509IncludeOption.EndCertOnly));
            }

            // Information on the these and other "key info clause" types can be found at:
            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm

            // Do it!
            signedXml.ComputeSignature();

            XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.ASSERTION);
            Assert.That(nodes.Count == 1);
            XmlNode node = nodes[0];
            doc.DocumentElement.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), node); 
        }
Esempio n. 27
0
        /// <summary>
        /// Signs the specified xml document with the certificate found in
        /// the local machine matching the provided friendly name and 
        /// referring to the specified target reference ID.
        /// </summary>
        /// <param name="certFriendlyName">
        /// Friendly Name of the X509Certificate to be retrieved
        /// from the LocalMachine keystore and used to sign the xml document.
        /// Be sure to have appropriate permissions set on the keystore.
        /// </param>
        /// <param name="xmlDoc">
        /// XML document to be signed.
        /// </param>
        /// <param name="targetReferenceId">
        /// Reference element that will be specified as signed.
        /// </param>
        /// <param name="includePublicKey">
        /// Flag to determine whether to include the public key in the 
        /// signed xml.
        /// </param>       
        /// <param name="serviceProviderInstance">
        /// ServiceProvider instance for retreaving Signature transform 
        /// and canonicalization method
        /// </param>
        public static void SignXml(string certFriendlyName, IXPathNavigable xmlDoc, string targetReferenceId, bool includePublicKey, ServiceProvider serviceProviderInstance)
        {
            if (string.IsNullOrEmpty(certFriendlyName))
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidCertFriendlyName);
            }

            if (xmlDoc == null)
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidXml);
            }

            if (string.IsNullOrEmpty(targetReferenceId))
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidTargetRefId);
            }

            X509Certificate2 cert = FedletCertificateFactory.GetCertificateByFriendlyName(certFriendlyName);
            if (cert == null)
            {
                throw new Saml2Exception(Resources.SignedXmlCertNotFound);
            }

            XmlDocument xml = (XmlDocument)xmlDoc;
            SignedXml signedXml = new SignedXml(xml);
            signedXml.SigningKey = cert.PrivateKey;

            if (includePublicKey)
            {
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));
                signedXml.KeyInfo = keyInfo;
            }

            Reference reference = new Reference();
            reference.Uri = "#" + targetReferenceId;

            //Read the transform type and canonicalization method from sp-extended.xml
            string transformType = serviceProviderInstance.SignatureTransformMethod;
            string canonicalizationMethodType = serviceProviderInstance.CanonicalizationMethod;
            Transform sigTransform;

            //Implement the gathered data
            switch(transformType){
                case "XmlDsigExcC14NTransform":
                    sigTransform = new XmlDsigExcC14NTransform();
                    break;
                case "XmlDsigExcC14NWithCommentsTransform":
                    sigTransform = new XmlDsigExcC14NWithCommentsTransform();
                    break;    
                default: 
                    sigTransform = new XmlDsigEnvelopedSignatureTransform();
                    break;
            }

            if (canonicalizationMethodType != null && 
                    (canonicalizationMethodType == SignedXml.XmlDsigExcC14NTransformUrl 
                    || canonicalizationMethodType == SignedXml.XmlDsigExcC14NWithCommentsTransformUrl))
                    {
                        signedXml.Signature.SignedInfo.CanonicalizationMethod = canonicalizationMethodType;
                    }
            
            reference.AddTransform(sigTransform);
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            XmlElement xmlSignature = signedXml.GetXml();
 
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xml.NameTable);
            nsMgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            nsMgr.AddNamespace("saml", Saml2Constants.NamespaceSamlAssertion);
            nsMgr.AddNamespace("samlp", Saml2Constants.NamespaceSamlProtocol);

            XmlNode issuerNode = xml.DocumentElement.SelectSingleNode("saml:Issuer", nsMgr);
            if (issuerNode != null)
            {
                xml.DocumentElement.InsertAfter(xmlSignature, issuerNode);
            }
            else
            {
                // Insert as a child to the target reference id
                XmlNode targetNode = xml.DocumentElement.SelectSingleNode("//*[@ID='" + targetReferenceId + "']", nsMgr);
                targetNode.PrependChild(xmlSignature);
            }
        }
Esempio n. 28
0
        private string SignAuthN(string authNXml, string requestId, X509Certificate2 requestSigningCert)
        {
            if (string.IsNullOrEmpty(authNXml))
                throw new ArgumentNullException("authNXml");

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

            SignedXml signedXml = new SignedXml(xmlDoc);

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(requestSigningCert));

            signedXml.KeyInfo = keyInfo;

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)requestSigningCert.PrivateKey;

            signedXml.SigningKey = rsaKey;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "#" + requestId;

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            XmlDsigExcC14NTransform c16n = new XmlDsigExcC14NTransform();
            c16n.InclusiveNamespacesPrefixList = "#default samlp saml ds xs xsi";
            reference.AddTransform(c16n);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), xmlDoc.DocumentElement.FirstChild);  //signature to be second node after saml:Issuer

            return xmlDoc.OuterXml;
        }
Esempio n. 29
0
        public virtual void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            else
            {
                Uri            = null;
                TransformChain = new TransformChain();

                foreach (XmlNode n in value.ChildNodes)
                {
                    if (n is XmlWhitespace)
                    {
                        continue;
                    }

                    switch (n.LocalName)
                    {
                    case XmlEncryption.ElementNames.Transforms:
                        foreach (XmlNode xn in ((XmlElement)n).GetElementsByTagName(XmlSignature.ElementNames.Transform, XmlSignature.NamespaceURI))
                        {
                            Transform t = null;
                            switch (((XmlElement)xn).Attributes [XmlSignature.AttributeNames.Algorithm].Value)
                            {
                            case XmlSignature.AlgorithmNamespaces.XmlDsigBase64Transform:
                                t = new XmlDsigBase64Transform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigC14NTransform:
                                t = new XmlDsigC14NTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigC14NWithCommentsTransform:
                                t = new XmlDsigC14NWithCommentsTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigEnvelopedSignatureTransform:
                                t = new XmlDsigEnvelopedSignatureTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigXPathTransform:
                                t = new XmlDsigXPathTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigXsltTransform:
                                t = new XmlDsigXsltTransform();
                                break;

#if NET_2_0
                            case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NTransform:
                                t = new XmlDsigExcC14NTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDsigExcC14NWithCommentsTransform:
                                t = new XmlDsigExcC14NWithCommentsTransform();
                                break;

                            case XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform:
                                t = new XmlDecryptionTransform();
                                break;
#endif
                            default:
                                continue;
                            }

                            t.LoadInnerXml(((XmlElement)xn).ChildNodes);
                            TransformChain.Add(t);
                        }
                        break;
                    }
                }

                if (value.HasAttribute(XmlEncryption.AttributeNames.URI))
                {
                    Uri = value.Attributes [XmlEncryption.AttributeNames.URI].Value;
                }
            }
        }
        /// <summary>
        /// Signs a XML file (enveloping signature) using a digital certificate
        /// </summary>
        /// <param name="xml">The XML data to sign represented as byte array</param>
        /// <param name="certFile">The certificate file to use for signing</param>
        /// <param name="certPassword">The certificate password</param>
        /// <param name="signWithSha256">Sign the document using SHA-256</param>
        /// <returns>The signed data represented as byte array</returns>
        private static byte[] SignEnvelopingXml(byte[] xml, string certFile, string certPassword, bool signWithSha256)
        {
            if (xml == null || xml.Length == 0)
            {
                // invalid XML array
                throw new Exception("Nothing to sign!");
            }

            // load certificate
            X509Certificate2 certificate = LoadSigningCertificate(certFile, certPassword, signWithSha256);

            if (!certificate.HasPrivateKey)
            {
                // invalid certificate
                throw new Exception("Specified certificate not suitable for signing!");
            }

            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);

                // craete transform (for canonicalization method & reference)
                XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform();

                // create new SignedXml from XmlDocument
                SignedXml signed = GenerateSignedXml(doc, certificate, signWithSha256);
                signed.SignedInfo.CanonicalizationMethod = transform.Algorithm;

                // get nodes (use XPath to include FATCA declaration)
                XmlNodeList nodes = doc.DocumentElement.SelectNodes("/*");

                // define data object
                DataObject dataObject = new DataObject() { Data = nodes, Id = "FATCA" };

                // add the data we are signing as a sub-element (object) of the signature element
                signed.AddObject(dataObject);

                // create reference
                Reference reference = new Reference(string.Format("#{0}", dataObject.Id));
                reference.AddTransform(transform);

                if (signWithSha256)
                {
                    // SHA-256 digest
                    reference.DigestMethod = RSAPKCS1SHA256SignatureDescription.ReferenceDigestMethod;
                }

                // add reference to document
                signed.AddReference(reference);

                // include KeyInfo object & compute signature
                signed.KeyInfo = CreateKeyInfoFromCertificate(certificate);
                signed.ComputeSignature();

                // get signature
                XmlElement xmlDigitalSignature = signed.GetXml();

                // XML declaration
                string xmlDeclaration = string.Empty;

                if (doc.FirstChild is XmlDeclaration)
                {
                    // include declaration
                    xmlDeclaration = doc.FirstChild.OuterXml;
                }

                // return signature as byte array
                return Encoding.UTF8.GetBytes(string.Concat(xmlDeclaration, xmlDigitalSignature.OuterXml));
            }
        }
Esempio n. 31
0
		public void PropagatedNamespaces ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.AppendChild (doc.CreateElement ("foo", "urn:foo"));
			doc.DocumentElement.AppendChild (doc.CreateElement ("bar", "urn:bar"));
			Assert.AreEqual (String.Empty, doc.DocumentElement.GetAttribute ("xmlns:f"), "#1");
			XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform ();
			t.LoadInput (doc);
			t.PropagatedNamespaces.Add ("f", "urn:foo");
			t.PropagatedNamespaces.Add ("b", "urn:bar");
			Stream s = t.GetOutput () as Stream;
			Assert.AreEqual (new StreamReader (s, Encoding.UTF8).ReadToEnd (), "<f:foo xmlns:f=\"urn:foo\"><b:bar xmlns:b=\"urn:bar\"></b:bar></f:foo>");
			Assert.AreEqual ("urn:foo", doc.DocumentElement.GetAttribute ("xmlns:f"), "#2");
		}
 private static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldFormat)
 {
     if (oldFormat)
     {
         XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform();
         transform.LoadInput(manifestDom);
         using (SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider())
         {
             byte[] buffer = provider.ComputeHash(transform.GetOutput() as MemoryStream);
             if (buffer == null)
             {
                 throw new CryptographicException(-2146869232);
             }
             return buffer;
         }
     }
     XmlDocument document = new XmlDocument {
         PreserveWhitespace = true
     };
     using (TextReader reader = new StringReader(manifestDom.OuterXml))
     {
         XmlReaderSettings settings = new XmlReaderSettings {
             DtdProcessing = DtdProcessing.Parse
         };
         XmlReader reader2 = XmlReader.Create(reader, settings, manifestDom.BaseURI);
         document.Load(reader2);
     }
     XmlDsigExcC14NTransform transform2 = new XmlDsigExcC14NTransform();
     transform2.LoadInput(document);
     using (SHA1CryptoServiceProvider provider2 = new SHA1CryptoServiceProvider())
     {
         byte[] buffer2 = provider2.ComputeHash(transform2.GetOutput() as MemoryStream);
         if (buffer2 == null)
         {
             throw new CryptographicException(-2146869232);
         }
         return buffer2;
     }
 }
        private SignatureVerificationResult VerifyAuthenticodeExpectedHash(XmlElement licenseNode)
        {
            Debug.Assert(licenseNode != null, "licenseNode != null");

            // Get the expected hash value from the signature
            XmlElement manifestInformation = licenseNode.SelectSingleNode("r:grant/as:ManifestInformation",
                                                                          m_namespaceManager) as XmlElement;

            if (manifestInformation == null)
            {
                return(SignatureVerificationResult.BadSignatureFormat);
            }

            string expectedHashString = manifestInformation.GetAttribute("Hash");

            if (String.IsNullOrEmpty(expectedHashString))
            {
                return(SignatureVerificationResult.BadSignatureFormat);
            }

            // The expected hash value is stored in backward order, so we cannot use a standard hex to bytes
            // routine to decode it.
            byte[] expectedHash = BackwardHexToBytes(expectedHashString);

            // Make a normalized copy of the manifest without the strong name signature attached
            XmlDocument normalizedManifest = new XmlDocument();

            normalizedManifest.PreserveWhitespace = true;

            XmlReaderSettings normalizationSettings = new XmlReaderSettings();

            normalizationSettings.DtdProcessing = DtdProcessing.Parse;

            using (TextReader manifestReader = new StringReader(m_manifestXml.OuterXml))
                using (XmlReader xmlReader = XmlReader.Create(manifestReader, normalizationSettings, m_manifestXml.BaseURI)) {
                    normalizedManifest.Load(xmlReader);
                }

            XmlElement signatureNode = normalizedManifest.SelectSingleNode("//asm:assembly/ds:Signature",
                                                                           m_namespaceManager) as XmlElement;

            Debug.Assert(signatureNode != null, "signatureNode != null");

            signatureNode.ParentNode.RemoveChild(signatureNode);

            // calculate the hash value of the manifest
            XmlDsigExcC14NTransform canonicalizedXml = new XmlDsigExcC14NTransform();

            canonicalizedXml.LoadInput(normalizedManifest);

            byte[] actualHash = null;
            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
                actualHash = sha1.ComputeHash(canonicalizedXml.GetOutput() as MemoryStream);
            }

            if (!CompareBytes(expectedHash, actualHash))
            {
                return(SignatureVerificationResult.BadDigest);
            }

            return(SignatureVerificationResult.Valid);
        }
Esempio n. 34
0
        private static XmlDocument SignXml()
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(".\\certificates\\samlRequestTemplate.xml");
            X509Certificate2 certificate = CertificateHelper.GetCertificate(".\\certificates\\HuaweiCA.p12", "Pr0d1234");

            //AsymmetricAlgorithm key = certificate.PrivateKey;
            AsymmetricAlgorithm key = certificate.PrivateKey;

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            ns.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

            XmlElement issuerNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Issuer", ns);

            SignedXml signedXml = new SignedXml(xmlDoc.DocumentElement);
            signedXml.SigningKey = key;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            KeyInfo keyInfo = new KeyInfo();

            //XmlDocument keyDoc = new XmlDocument();

            //keyDoc.LoadXml(certificate.PublicKey.Key.ToXmlString(false));
            //keyInfo.LoadXml(keyDoc.DocumentElement);
            keyInfo.AddClause(new KeyInfoX509Data(certificate));
            signedXml.KeyInfo = keyInfo;

            string refId = xmlDoc.DocumentElement.GetAttribute("ID");

            Reference reference = new Reference();
            reference.Uri = "#" + refId;

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform();
            env2.InclusiveNamespacesPrefixList = "#default code ds kind rw saml samlp typens";
            reference.AddTransform(env2);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();
            xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), issuerNode);

            //xmlDoc.NameTable.Add("samlp");
            //XmlElement nameIDPolicyElem = xmlDoc.CreateElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol");
            //nameIDPolicyElem.SetAttribute("AllowCreate", "False");

            //xmlDoc.DocumentElement.AppendChild(nameIDPolicyElem);

            xmlDoc.Save("samleRequestCSharp.xml");

            return xmlDoc;
        }
Esempio n. 35
0
		public void DigestValue_LF ()
		{
			XmlDocument doc = CreateSomeXml ("\n");
			XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform ();
			transform.LoadInput (doc);
			Stream s = (Stream) transform.GetOutput ();
			string output = Stream2String (s);
			Assert.AreEqual ("<person>\n  <birthplace>Brussels</birthplace>\n</person>", output, "#1");

			s.Position = 0;

			HashAlgorithm hash = HashAlgorithm.Create ("System.Security.Cryptography.SHA1CryptoServiceProvider");
			byte[] digest = hash.ComputeHash (s);
			Assert.AreEqual ("e3dsi1xK8FAx1vsug7J203JbEAU=", Convert.ToBase64String (digest), "#2");

			X509Certificate2 cert = new X509Certificate2 (_pkcs12, "mono");
			SignedXml signedXml = new SignedXml (doc);
			signedXml.SigningKey = cert.PrivateKey;
			signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

			Reference reference = new Reference ();
			reference.Uri = "";

			XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform ();
			reference.AddTransform (env);
			signedXml.AddReference (reference);

			KeyInfo keyInfo = new KeyInfo ();
			KeyInfoX509Data x509KeyInfo = new KeyInfoX509Data ();
			x509KeyInfo.AddCertificate (new X509Certificate2 (_cert));
			x509KeyInfo.AddCertificate (cert);
			keyInfo.AddClause (x509KeyInfo);
			signedXml.KeyInfo = keyInfo;

			signedXml.ComputeSignature ();

			digest = reference.DigestValue;
			Assert.AreEqual ("e3dsi1xK8FAx1vsug7J203JbEAU=", Convert.ToBase64String (digest), "#3");

			Assert.AreEqual ("<SignedInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" 
				+ "<CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" />"
				+ "<SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\" />"
				+ "<Reference URI=\"\">"
				+ "<Transforms>"
				+ "<Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" />"
				+ "</Transforms>"
				+ "<DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" />"
				+ "<DigestValue>e3dsi1xK8FAx1vsug7J203JbEAU=</DigestValue>"
				+ "</Reference>"
				+ "</SignedInfo>", signedXml.SignedInfo.GetXml ().OuterXml, "#4");
		}
        /// <summary>
        ///     Verify the hash of the manifest without any signature attached is what the Authenticode
        ///     signature expects it to be
        /// </summary>
        private SignatureVerificationResult VerifyAuthenticodeExpectedHash(XmlElement licenseNode) {
            Debug.Assert(licenseNode != null, "licenseNode != null");

            // Get the expected hash value from the signature
            XmlElement manifestInformation = licenseNode.SelectSingleNode("r:grant/as:ManifestInformation",
                                                                          m_namespaceManager) as XmlElement;
            if (manifestInformation == null)
                return SignatureVerificationResult.BadSignatureFormat;

            string expectedHashString = manifestInformation.GetAttribute("Hash");
            if (String.IsNullOrEmpty(expectedHashString)) {
                return SignatureVerificationResult.BadSignatureFormat;
            }

            // The expected hash value is stored in backward order, so we cannot use a standard hex to bytes
            // routine to decode it.
            byte[] expectedHash = BackwardHexToBytes(expectedHashString);

            // Make a normalized copy of the manifest without the strong name signature attached
            XmlDocument normalizedManifest = new XmlDocument();
            normalizedManifest.PreserveWhitespace = true;

            XmlReaderSettings normalizationSettings = new XmlReaderSettings();
            normalizationSettings.DtdProcessing = DtdProcessing.Parse;

            using (TextReader manifestReader = new StringReader(m_manifestXml.OuterXml))
            using (XmlReader xmlReader = XmlReader.Create(manifestReader, normalizationSettings, m_manifestXml.BaseURI)) {
                normalizedManifest.Load(xmlReader);
            }

            XmlElement signatureNode = normalizedManifest.SelectSingleNode("//asm:assembly/ds:Signature",
                                                                           m_namespaceManager) as XmlElement;
            Debug.Assert(signatureNode != null, "signatureNode != null");

            signatureNode.ParentNode.RemoveChild(signatureNode);

            // calculate the hash value of the manifest
            XmlDsigExcC14NTransform canonicalizedXml = new XmlDsigExcC14NTransform();
            canonicalizedXml.LoadInput(normalizedManifest);

            byte[] actualHash = null;
            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
                actualHash = sha1.ComputeHash(canonicalizedXml.GetOutput() as MemoryStream);
            }

            if (!CompareBytes(expectedHash, actualHash)) {
                return SignatureVerificationResult.BadDigest;
            }

            return SignatureVerificationResult.Valid;
        }