Ejemplo n.º 1
2
        public override object EncodeCMS(X509Certificate2 certificate, string xmlFilePath)
        {
            XmlDocument Document = new XmlDocument();
            Document.PreserveWhitespace = true;
            XmlTextReader XmlFile = new XmlTextReader(xmlFilePath);
            Document.Load(XmlFile);
            XmlFile.Close();
            XmlNodeList SignaturesList = Document.GetElementsByTagName("Signature");
            // Remove existing signatures, this is not a countersigning.
            for (int i = 0; i < SignaturesList.Count; i++)
            {
                SignaturesList[i].ParentNode.RemoveChild(SignaturesList[i]);
                i--;
            }

            SignedXml SignedXml = new SignedXml(Document);
            SignedXml.SigningKey = certificate.PrivateKey;
            Reference Reference = new Reference();
            Reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform EnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
            Reference.AddTransform(EnvelopedSignatureTransform);
            SignedXml.AddReference(Reference);
            KeyInfo Key = new KeyInfo();
            Key.AddClause(new KeyInfoX509Data(certificate));
            SignedXml.KeyInfo = Key;
            SignedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement XmlDigitalSignature = SignedXml.GetXml();

            return XmlDigitalSignature;
        }
Ejemplo n.º 2
1
        // Sign an XML file.  
        // This document cannot be verified unless the verifying  
        // code has the key with which it was signed. 
        public static void SignXml(XmlDocument xmlDoc, RSA Key)
        {
            // Check arguments. 
            if (xmlDoc == null)
                throw new ArgumentException("xmlDoc");
            if (Key == null)
                throw new ArgumentException("Key");

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;

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

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

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

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

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

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
        private static string SignXml(XmlDocument unsignedXml,
                                        AsymmetricAlgorithm key)
        {
            if (unsignedXml.DocumentElement == null)
            {
                throw new ArgumentNullException("unsignedXml");
            }

            // Create a reference to be signed. Blank == Everything
                var emptyReference = new Reference { Uri = "" };

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

            var signedXml = new SignedXml(unsignedXml) { SigningKey = key };
            signedXml.AddReference(emptyReference);
            signedXml.ComputeSignature();

            var digitalSignature = signedXml.GetXml();
       
                unsignedXml.DocumentElement.AppendChild(
                    unsignedXml.ImportNode(digitalSignature, true));

            var signedXmlOut = new StringBuilder();
            using (var swOut = new StringWriter(signedXmlOut))
            {
                unsignedXml.Save(swOut);
            }

            return signedXmlOut.ToString();
        }
Ejemplo n.º 4
0
        public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert)
        {
            if(xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            var signedXml = new SignedXml(xmlDocument);

            signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey;

            var reference = new Reference();
            reference.Uri = "";
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signedXml.GetXml(), true));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Adds a digital signature to the outgoing request message, before sending it to Acquirer.
        /// </summary>
        /// <param name="requestXml">
        /// The unsigned request XML message.
        /// </param>
        /// <returns>
        /// The request message, including digital signature.
        /// </returns>
        public string SignRequestXml(XDocument requestXml)
        {
            XmlDocument document = ToXmlDocument(requestXml);

            RSACryptoServiceProvider key = ExtractPrivateKeyFrom(acceptantPrivateCertificate);

            var signedXml = new SignedXml(document) { SigningKey = key };
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";

            // Add a signing reference, the uri is empty and so the whole document is signed. 
            var reference = new Reference { DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256" };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.Uri = "";
            signedXml.AddReference(reference);

            // Add the certificate as key info. Because of this, the certificate 
            // with the public key will be added in the signature part. 
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoName(acceptantPrivateCertificate.Thumbprint));
            signedXml.KeyInfo = keyInfo;

            // Generate the signature. 
            signedXml.ComputeSignature();

            XmlElement xmlSignature = signedXml.GetXml();
            document.DocumentElement.AppendChild(document.ImportNode(xmlSignature, true));

            // Check that outgoing signature is valid. Private certificate also contains public part.
            VerifyDocumentSignature(document, acceptantPrivateCertificate);

            return GetContentsFrom(document);
        }
        /// <summary>
        /// Use an X509 certificate to append a computed signature to an XML serialized Response
        /// </summary>
        /// <param name="XMLSerializedSAMLResponse"></param>
        /// <param name="ReferenceURI">Assertion ID from SAML Response</param>
        /// <param name="SigningCert">X509 Certificate for signing</param>
        /// <remarks>Referenced this article:
        ///     http://www.west-wind.com/weblog/posts/2008/Feb/23/Digitally-Signing-an-XML-Document-and-Verifying-the-Signature
        /// </remarks>
        public static void AppendSignatureToXMLDocument(ref XmlDocument XMLSerializedSAMLResponse, String ReferenceURI, X509Certificate2 SigningCert)
        {
            XmlNamespaceManager ns = new XmlNamespaceManager(XMLSerializedSAMLResponse.NameTable);
            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            XmlElement xeAssertion = XMLSerializedSAMLResponse.DocumentElement.SelectSingleNode("saml:Assertion", ns) as XmlElement;

            //SignedXml signedXML = new SignedXml(XMLSerializedSAMLResponse);
            SignedXml signedXML = new SignedXml(xeAssertion);

            signedXML.SigningKey = SigningCert.PrivateKey;
            signedXML.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            Reference reference = new Reference();
            reference.Uri = ReferenceURI;
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXML.AddReference(reference);
            signedXML.ComputeSignature();

            XmlElement signature = signedXML.GetXml();

            XmlElement xeResponse = XMLSerializedSAMLResponse.DocumentElement;

            xeResponse.AppendChild(signature);
        }
Ejemplo n.º 7
0
        public static string Sign(string xml, X509Certificate2 certificate)
        {
            if (xml == null) throw new ArgumentNullException("xml");
            if (certificate == null) throw new ArgumentNullException("certificate");
            if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key");

            XmlDocument doc = new XmlDocument();

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

            SignedXml signedXml = new SignedXml(doc);
            signedXml.SigningKey = certificate.PrivateKey;

            // Attach certificate KeyInfo
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Attach transforms
            var reference = new Reference("");
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
            reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
            signedXml.AddReference(reference);

            // Compute signature
            signedXml.ComputeSignature();
            var signatureElement = signedXml.GetXml();

            // Add signature to bundle
            doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));

            return doc.OuterXml;
        }
Ejemplo n.º 8
0
        public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert)
        {
            if (xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            var signedXml = new SignedXml(xmlDocument);

            // The transform XmlDsigExcC14NTransform and canonicalization method XmlDsigExcC14NTransformUrl is important for partially signed XML files
            // see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.signedxml.xmldsigexcc14ntransformurl(v=vs.110).aspx
            // The reference URI has to be set correctly to avoid assertion injections
            // For both, the ID/Reference and the Transform/Canonicalization see as well: 
            // https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf section 5.4.2 and 5.4.3

            signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            var reference = new Reference { Uri = "#" + xmlDocument.DocumentElement.GetAttribute("ID") };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signedXml.GetXml(), true));
        }
Ejemplo n.º 9
0
        public XmlDocument assinaturaXmlEnviar(XmlDocument _xml)
        {
            XmlDocument xmlDocAss = _xml;

            try
            {


                if (cert == null)
                    throw new Exception("Nao foi encontrado o certificado: " + config.configNFCe.NomeCertificadoDigital);

                Reference reference = new Reference();
                SignedXml docXML = new SignedXml(xmlDocAss);

                docXML.SigningKey = cert.PrivateKey;
                XmlAttributeCollection uri = xmlDocAss.GetElementsByTagName("infNFe").Item(0).Attributes;
                foreach (XmlAttribute atributo in uri)
                {
                    if (atributo.Name == "Id")
                        reference.Uri = "#" + atributo.InnerText;
                }

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

                XmlDsigC14NTransform c14Transform = new XmlDsigC14NTransform();
                reference.AddTransform(c14Transform);
                docXML.AddReference(reference);

                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));

                docXML.KeyInfo = keyInfo;
                docXML.ComputeSignature();

                XmlElement xmlDigitalSignature = docXML.GetXml();

                foreach (var _nfe in xmlDocAss.GetElementsByTagName("NFe").Cast<XmlElement>())
                    _nfe.AppendChild(xmlDocAss.ImportNode(xmlDigitalSignature, true));


                xmlDocAss.PreserveWhitespace = true;
                return xmlDocAss;
            }

            catch (Exception e)
            {
                Utils.Logger.getInstance.error(e);
                return null;
                throw new Exception(e.ToString());
            }


        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            X509Store store = new X509Store("MY", StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

            X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
            var x509 = collection.Find(X509FindType.FindBySubjectName, "note-oberdan.pca.com.br", true);
            X509Certificate2 cert = x509[0];

            RSA rsa = (RSA)cert.PrivateKey;

            XmlDocument doc = new XmlDocument();

            doc.InnerXml = "<teste vl=\"1\"></teste>";


            SignedXml SignedDocument = new SignedXml();
            KeyInfo   keyInfo        = new KeyInfo();

            keyInfo.AddClause(new System.Security.Cryptography.Xml.KeyInfoX509Data(cert));
            SignedDocument = new System.Security.Cryptography.Xml.SignedXml(doc);

            //Seta chaves
            SignedDocument.SigningKey = rsa;
            SignedDocument.KeyInfo    = keyInfo;

            //Cria referencia
            Reference reference = new Reference();

            reference.Uri = String.Empty;

            //Adiciona transformacao a referencia
            reference.AddTransform(new
                                   System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new
                                   System.Security.Cryptography.Xml.XmlDsigC14NTransform(false));

            //Adiciona referencia ao xml
            SignedDocument.AddReference(reference);

            //Calcula Assinatura
            SignedDocument.ComputeSignature();

            //Pega representação da assinatura
            XmlElement xmlDigitalSignature = SignedDocument.GetXml();

            //Adiciona ao doc XML
            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

            doc.Save(@"C:\testes\ExemploAssinaturaXML\ExemploAssinaturaXML\xmlAssinado3.xml");
        }
Ejemplo n.º 11
0
        internal static XmlElement GetXmlDigitalSignature(XmlDocument doc, AsymmetricAlgorithm key) {
            if(IsDebugEnabled)
                log.Debug("암호화된 Xml 문서를 만듭니다...");

            var signedXml = new SignedXml(doc) { SigningKey = key };
            var reference = new Reference { Uri = string.Empty };

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            return signedXml.GetXml();
        }
        public string AssinarComCertificado(string textXML, X509Certificate2 certificado)
        {
            try
            {
                string xmlString = textXML;

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(xmlString);

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

                XmlDocument documentoNovo = new XmlDocument();
                documentoNovo.LoadXml(doc.OuterXml);

                SignedXml signedXml = new SignedXml(documentoNovo);

                signedXml.SigningKey = certificado.PrivateKey;

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

                XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                reference.AddTransform(c14);

                signedXml.AddReference(reference);

                KeyInfo keyInfo = new KeyInfo();

                keyInfo.AddClause(new KeyInfoX509Data(certificado));

                signedXml.KeyInfo = keyInfo;
                signedXml.ComputeSignature();

                XmlElement xmlDigitalSignature = signedXml.GetXml();

                XmlNode sign = doc.ImportNode(xmlDigitalSignature, true);
                doc.ChildNodes.Item(0).AppendChild(sign);

                XmlDocument XMLDoc = new XmlDocument();
                XMLDoc.PreserveWhitespace = false;
                XMLDoc = doc;

                return XMLDoc.OuterXml;

            } catch (Exception error)
            {
                throw new Exception(error.Message);
            }
        }
Ejemplo n.º 13
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;
        }
Ejemplo n.º 14
0
    /// <summary>
    ///		Firma un archivo XML con un certificado
    /// </summary>
		public void SignXmlDocument(XmlDocument objXMLDocument, X509Certificate2 objCertificate, string strReferenceToSign = "")
		{	SignedXml objSignedXml = new SignedXml(objXMLDocument);

				// Añade la clave al documento SignedXml
					objSignedXml.SigningKey = (RSACryptoServiceProvider) objCertificate.PrivateKey;
				// Asigna el identificador de referencia
					if (!string.IsNullOrWhiteSpace(strReferenceToSign))
						objSignedXml.AddReference(GetReference(strReferenceToSign));
				// Añade la información de los parámetros de firma
					objSignedXml.Signature.KeyInfo = GetKeyInfoFromCertificate(objCertificate);
				// Calcula la firma
					objSignedXml.ComputeSignature();
				// Añade el elemento firmado al documento XML
					objXMLDocument.DocumentElement.AppendChild(objXMLDocument.ImportNode(objSignedXml.GetXml(), true));
		}
        public static XmlElement GenerateSignature(XmlDocument licenseDocument, IPrivateCryptoKey privateKey)
        {
            using (var privateKeyProvider = new RsaPrivateKeyProvider())
            {
                var reference = new Reference { Uri = string.Empty };
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

                var signedXml = new SignedXml(licenseDocument) { SigningKey = privateKeyProvider.Recreate(privateKey) };

                signedXml.AddReference(reference);
                signedXml.ComputeSignature();

                return signedXml.GetXml();
            }
        }
Ejemplo n.º 16
0
    public void Sign(XmlDocument message, MessageType messageType)
    {
      XmlNode mainNode = this.getMainNode(message, messageType);
      if (mainNode == null) return;

      SetCryptoConfig.SetAlgorithm();

      SignedXml signedXml = new SignedXml(message);
      signedXml.SigningKey = this.settings.CryptoProvider;
      signedXml.AddReference(this.getReference(mainNode));
      signedXml.KeyInfo = this.getKeyInfo();
      signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
      signedXml.ComputeSignature();

      XmlElement xmlDigitalSignature = signedXml.GetXml();
      mainNode.AppendChild(xmlDigitalSignature);
    }
Ejemplo n.º 17
0
        public bool Execute()
        {
            Console.Out.WriteLine("Signing xml file");
            Console.Out.WriteLine("input file = {0}", _inputFile);
            Console.Out.WriteLine("output file = {0}", _signatureFile);
            Console.Out.WriteLine("key file = {0}", _keyFile);

            using (var key = new RSACryptoServiceProvider())
            {
                key.FromXmlString(File.ReadAllText(_keyFile));

                var doc = new XmlDocument {PreserveWhitespace = true};
                doc.Load(new XmlTextReader(_inputFile));

                var signedXml = new SignedXml(doc) {SigningKey = key};
                var xmlSignature = signedXml.Signature;

                var reference = new Reference("");
                var env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                xmlSignature.SignedInfo.AddReference(reference);
                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new RSAKeyValue(key));
                xmlSignature.KeyInfo = keyInfo;

                signedXml.ComputeSignature();

                var xmlDigitalSignature = signedXml.GetXml();

                using (var writer = new XmlTextWriter(_signatureFile, new UTF8Encoding(false)))
                {
                    var signatureDocument = new XmlDocument();
                    var importNode = signatureDocument.ImportNode(xmlDigitalSignature, true);

                    signatureDocument.AppendChild(importNode);

                    signatureDocument.WriteTo(writer);
                    writer.Close();
                }
            }

            Console.Out.WriteLine("done");

            return true;
        }
Ejemplo n.º 18
0
        private static void AddSignatureToXmlDocument(XmlDocument toSign, X509Certificate2 cert)
        {
            var signedXml = new SignedXml(toSign);
            signedXml.SigningKey = cert.PrivateKey;

            var reference = new Reference();
            reference.Uri = "";
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            var xmlDigitalSignature = signedXml.GetXml();
            toSign.DocumentElement.AppendChild(toSign.ImportNode(xmlDigitalSignature, true));
            if (toSign.FirstChild is XmlDeclaration) {
                toSign.RemoveChild(toSign.FirstChild);
            }
        }
Ejemplo n.º 19
0
        public string GenerateSignedXml(LicenseDetails details)
        {
            if (details == null)
                throw new ArgumentNullException("details");

            string rawXml;
            var serializer = new XmlSerializer(typeof (LicenseDetails));
            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, details);
                stream.Position = 0;

                using (var streamReader = new StreamReader(stream))
                    rawXml = streamReader.ReadToEnd();
            }

            // Sign the xml
            var doc = new XmlDocument();
            TextReader reader = new StringReader(rawXml);
            doc.Load(reader);
            var signedXml = new SignedXml(doc);
            signedXml.SigningKey = _key;

            var reference = new Reference { Uri = "" };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            var signature = signedXml.GetXml();
            if (doc.DocumentElement != null)
                doc.DocumentElement.AppendChild(doc.ImportNode(signature, true));

            if (doc.FirstChild is XmlDeclaration)
                doc.RemoveChild(doc.FirstChild);

            // Return the resulting xml
            using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
                doc.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();
                return stringWriter.GetStringBuilder().ToString();
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Sign
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="output">The output.</param>
        /// <param name="certificate">The certificate.</param>
        public override void Sign(Stream input, Stream output, X509Certificate2 certificate)
        {
            CheckInputOutputAndCertificate(input, output, certificate);

            using (var rsaKey = (RSACryptoServiceProvider)certificate.PrivateKey)
            {
                var xmlDoc = new XmlDocument { PreserveWhitespace = true };
                xmlDoc.Load(input);
                var signedXml = new SignedXml(xmlDoc) {SigningKey = rsaKey};
                var envelope = new XmlDsigEnvelopedSignatureTransform();
                var reference = new Reference {Uri = ""};
                reference.AddTransform(envelope);
                signedXml.AddReference(reference);
                signedXml.ComputeSignature();
                var xmlDigitalSignature = signedXml.GetXml();
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
                xmlDoc.Save(output);
            }
        }
        // code outline borrowed from: http://blogs.msdn.com/shawnfa/archive/2003/11/12/57030.aspx
        public static void Sign(XmlDocument doc, RSA key)
        {
            SignedXml signer = new SignedXml(doc);

            // setup the key used to sign 
            signer.KeyInfo = new KeyInfo();
            signer.KeyInfo.AddClause(new RSAKeyValue(key));
            signer.SigningKey = key;

            // create a reference to the root of the document 
            Reference orderRef = new Reference("");
            orderRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signer.AddReference(orderRef);

            // add transforms that only select the order items, type, and 
            // compute the signature, and add it to the document 
            signer.ComputeSignature();
            doc.DocumentElement.PrependChild(signer.GetXml());
        }
        /// <summary>
        /// Use an X509 certificate to append a computed signature to an XML serialized Response
        /// </summary>
        /// <param name="XMLSerializedSAMLResponse"></param>
        /// <param name="ReferenceURI">Assertion ID from SAML Response</param>
        /// <param name="SigningCert">X509 Certificate for signing</param>
        /// <remarks>Referenced this article:
        ///     http://www.west-wind.com/weblog/posts/2008/Feb/23/Digitally-Signing-an-XML-Document-and-Verifying-the-Signature
        /// </remarks>
        public static void AppendSignatureToXMLDocument(ref XmlDocument XMLSerializedSAMLResponse, String ReferenceURI, X509Certificate2 SigningCert)
        {
            SignedXml signedXML = new SignedXml(XMLSerializedSAMLResponse);

            signedXML.SigningKey = SigningCert.PrivateKey;
            signedXML.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            Reference reference = new Reference();
            reference.Uri = "#" + ReferenceURI;
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXML.AddReference(reference);
            signedXML.ComputeSignature();

            XmlElement signature = signedXML.GetXml();

            XmlElement xeResponse = XMLSerializedSAMLResponse.DocumentElement;

            xeResponse.AppendChild(signature);
        }
Ejemplo n.º 23
0
        public static string SignXml(string xml)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

            var signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = (RSACryptoServiceProvider)TestCert.PrivateKey;

            var reference = new Reference();
            reference.Uri = "";
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(signedXml.GetXml(), true));

            return xmlDoc.OuterXml;
        }
Ejemplo n.º 24
0
        public void ApplySignature(SamlResponse response, X509Certificate2 certificate, XmlDocument document)
        {
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoX509Data(certificate));

            var signedXml = new SignedXml(document)
            {
                SigningKey = certificate.PrivateKey,
                KeyInfo = keyInfo
            };

            var reference = new Reference(AssertionIdPrefix + response.Id);
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            var xml = signedXml.GetXml();

            document.FindChild(AssertionElem).AppendChild(xml);
        }
Ejemplo n.º 25
0
        public static string firmarDocumento(string documento, X509Certificate2 certificado)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            String documento2 = documento;

            doc.LoadXml(documento);
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SigningKey = certificado.PrivateKey;

            Signature XMLSignature = signedXml.Signature;

            Reference reference = new Reference("");

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

            XMLSignature.SignedInfo.AddReference(reference);

            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(new RSAKeyValue((RSA)certificado.PrivateKey));

            keyInfo.AddClause(new KeyInfoX509Data(certificado));

            XMLSignature.KeyInfo = keyInfo;

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return doc.InnerXml;
        }
Ejemplo n.º 26
0
        public static void SignXmlDocument(Stream sourceXmlFile,
            Stream destinationXmlFile, X509Certificate2 certificate)
        {
            // Carico il documento XML
            XmlDocument doc = new XmlDocument();
            doc.Load(sourceXmlFile);

            // Preparo un DOMDocument che conterrà il risultato
            XmlDocument outputDocument = new XmlDocument();

            // Recupero un riferimento all'intero contenuto del documento XML
            XmlNodeList elementsToSign = doc.SelectNodes(String.Format("/{0}", doc.DocumentElement.Name));

            // Costruisco la firma
            SignedXml signedXml = new SignedXml();
            System.Security.Cryptography.Xml.DataObject dataSignature =
                new System.Security.Cryptography.Xml.DataObject();
            dataSignature.Data = elementsToSign;
            dataSignature.Id = doc.DocumentElement.Name;
            signedXml.AddObject(dataSignature);
            Reference reference = new Reference();
            reference.Uri = String.Format("#{0}", dataSignature.Id);
            signedXml.AddReference(reference);

            if ((certificate != null) && (certificate.HasPrivateKey))
            {
                signedXml.SigningKey = certificate.PrivateKey;

                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(certificate));
                signedXml.KeyInfo = keyInfo;
                signedXml.ComputeSignature();

                // Aggiungo la firma al nuovo documento di output
                outputDocument.AppendChild(
                    outputDocument.ImportNode(signedXml.GetXml(), true));

                outputDocument.Save(destinationXmlFile);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 对传入xml文档对象进行签名
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="signXmlDoc">待签名的xml文档对象</param>
        /// <returns>返回签名后的xml文本</returns>
        public static string Signature(string privateKey, string xmlString)
        {
            var _RSAProvider = new RSACryptoServiceProvider(keyLength);
            _RSAProvider.FromXmlString(privateKey);

            XmlDocument signXmlDoc = LoadXml(xmlString);

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(signXmlDoc);
            // Add the key to the SignedXml document. 
            signedXml.SigningKey = _RSAProvider;

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

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

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

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

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

            // Append the element to the XML document.
            signXmlDoc.DocumentElement.AppendChild(signXmlDoc.ImportNode(xmlDigitalSignature, true));

            if (signXmlDoc.FirstChild is XmlDeclaration)
            {
                signXmlDoc.RemoveChild(signXmlDoc.FirstChild);
            }
            return FormatXml(signXmlDoc);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Erzeugt für das übergebene XML-Dokument eine Signatur 
        /// und fügt diese in das Dokument ein
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public XmlDocument SignDocument(XmlDocument doc)
        {
            // Erstelle eine Referenz für die Transformation und
            // füge diese Referenz dem Signatur-Wrapper hinzu
            Reference reference = new Reference();
            reference.Uri = String.Empty;

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

            // Erstelle den Signatur-Wrapper mit Schlüsselinformationen
            SignedXml signedDoc = new SignedXml(doc);
            signedDoc.SigningKey = rsa;
            signedDoc.AddReference(reference);

            // Berechne die Signatur
            signedDoc.ComputeSignature();

            // Füge die Signatur in das XML-Dokument ein und gebe es zurück
            doc.DocumentElement.AppendChild(doc.ImportNode(signedDoc.GetXml(), true));

            return doc;
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            var xml = "<xml><a ID=\"foo\"><content>foo-content</content><Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\" /></a><a ID=\"bar\"><content>bar-content</content><Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\" /></a></xml>";

            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);

            var key = new RSACryptoServiceProvider();

            var sign = new SignedXml(xmlDocument);
            var reference2 = new Reference("#bar");
            reference2.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            sign.AddReference(reference2);
            sign.SigningKey = key;
            sign.ComputeSignature();
            var barNode = (XmlElement)xmlDocument.SelectSingleNode("//*[@ID=\"bar\"]");
            barNode.AppendChild(xmlDocument.ImportNode(sign.GetXml(), true));

            var barSignature = barNode.ChildNodes.OfType<XmlElement>()
                .Single(x => x.LocalName == "Signature" && x.HasChildNodes);

            WriteLine("== Xml document ==");
            WriteLine(xmlDocument.OuterXml);
            WriteLine();

            var verify = new SignedXml(xmlDocument);
            verify.LoadXml(barSignature);
            WriteLine("Check Signature: " + verify.CheckSignature(key));

            WriteLine();
            WriteLine("Reloading SignedXml and fixing signature index...");
            verify.LoadXml(barSignature);
            FixSignatureIndex(verify, barSignature);
            WriteLine("Check Signature: " + verify.CheckSignature(key));

            ReadLine();
        }
Ejemplo n.º 30
0
        public string SignXml(XmlDocument Document, X509Certificate2 cert)
        {
            SignedXml signedXml = new SignedXml(Document);
            signedXml.SigningKey = cert.PrivateKey;
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";

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

            //canonicalize
            XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
            reference.AddTransform(c14t);

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);

            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

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

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

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

            Document.DocumentElement.AppendChild(
                Document.ImportNode(xmlDigitalSignature, true));
            return Document.OuterXml;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Gera assinatura Digital do XML
        /// </summary>
        /// <param name="XMLString"></param>
        /// <param name="RefUri"></param>
        /// <param name="X509Cert"></param>
        /// <returns></returns>
        public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert)
        {


            int resultado = 0;
            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                //   certificado para ser utilizado na assinatura
                //
                string _xnome = "";

                bool bX509Cert = false;

                if (X509Cert != null)
                {
                    _xnome = X509Cert.Subject.ToString();
                }
                else
                {
                    bX509Cert = true;
                }
                X509Certificate2 _X509Cert = new X509Certificate2();
                X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, (object)_xnome, true);

                //if (collection1.Count == 0)
                if (bX509Cert)
                {
                    resultado = 2;
                    msgResultado = "Problemas no certificado digital";
                }
                else
                {
                    // certificado ok
                    //_X509Cert = collection1[0];

                    _X509Cert = X509Cert;
                    string x;
                    x = _X509Cert.GetKeyAlgorithm().ToString();
                    // Create a new XML document.

                    XmlDocument doc = new XmlDocument();

                    // Format the document to ignore white spaces.
                    doc.PreserveWhitespace = false;

                    // Load the passed XML file using it's name.
                    try
                    {
                        doc.LoadXml(XMLString);

                        // Verifica se a tag a ser assinada existe é única
                        int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;

                        if (qtdeRefUri == 0)
                        {
                            //  a URI indicada não existe
                            resultado = 4;
                            msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
                        }
                        // Exsiste mais de uma tag a ser assinada
                        else
                        {

                            if (qtdeRefUri > 1)
                            {
                                // existe mais de uma URI indicada
                                resultado = 5;
                                msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";

                            }
                            else
                            {
                                try
                                {
                                    //Claudinei - o.s. 23615 - 10/08/2009
                                    //for (int i = 0; i < qtdeRefUri; i++)
                                    {
                                        //Fim - Claudinei - o.s. 23615 - 10/08/2009

                                        // Create a SignedXml object.
                                        SignedXml signedXml = new SignedXml(doc);

                                        //sTipoAssinatura = _X509Cert.PrivateKey.KeySize.ToString();
                                        // Add the key to the SignedXml document 
                                        signedXml.SigningKey = _X509Cert.PrivateKey;

                                        // Create a reference to be signed
                                        Reference reference = new Reference();
                                        // pega o uri que deve ser assinada
                                        XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes; //Claudinei - o.s. 23615 - 10/08/2009
                                        foreach (XmlAttribute _atributo in _Uri)
                                        {
                                            if (_atributo.Name == "Id")
                                            {
                                                reference.Uri = "#" + _atributo.InnerText;
                                            }
                                        }

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

                                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                        reference.AddTransform(c14);

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

                                        // Create a new KeyInfo object
                                        KeyInfo keyInfo = new KeyInfo();

                                        // Load the certificate into a KeyInfoX509Data object
                                        // and add it to the KeyInfo object.
                                        keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));

                                        // Add the KeyInfo object to the SignedXml object.
                                        signedXml.KeyInfo = keyInfo;

                                        signedXml.ComputeSignature();

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

                                        // Append the element to the XML document.

                                        //Claudinei - o.s. 23581 - 07/07/2009
                                        /*
                                        string teste = "";
                                        //XmlNode xmlno = new XmlNode();
                                        foreach (XmlNode xmlno in doc)
                                        {
                                            teste = xmlno.Name.ToString();
                                        }
                                         */
                                        //Fim - Claudinei - o.s. 23581 - 07/07/2009

                                        //Danner - o.s. 23732 - 11/11/2009
                                        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                        //Fim - Danner - o.s. 23732 - 11/11/2009
                                        XMLDoc = new XmlDocument();
                                        XMLDoc.PreserveWhitespace = false;
                                        XMLDoc = doc;
                                    } //Claudinei - o.s. 23615 - 10/08/2009
                                }

                                catch (Exception caught)
                                {
                                    resultado = 7;
                                    msgResultado = "Erro: Ao assinar o documento - " + caught.Message;
                                }

                            }
                        }
                    }

                    catch (Exception caught)
                    {
                        resultado = 3;
                        msgResultado = "Erro: XML mal formado - " + caught.Message;
                    }
                }
            }
            catch (Exception caught)
            {
                resultado = 1;
                msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message;
            }

            return resultado;
        }