Beispiel #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;
        }
Beispiel #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();
        }
        /// <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);
        }
        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));
        }
        /// <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);
        }
        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;
        }
        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));
        }
Beispiel #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());
            }


        }
Beispiel #10
0
        public  string SignXml(XDocument xml)
        {
          using (MemoryStream streamIn = new MemoryStream())
          {
            xml.Save(streamIn);
            streamIn.Position = 0;
          //  var rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; // Create rsa crypto provider from private key contained in certificate, weirdest cast ever!;



           // string sCertFileLocation = @"C:\plugins\idealtest\bin\Debug\certficate.pfx";
           // X509Certificate2 certificate = new X509Certificate2(sCertFileLocation, "D3M@ast3rsR0cks");
            RSA rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(streamIn);

            SignedXml signedXml = new SignedXml(xmlDoc);
            signedXml.SigningKey = rsaKey;

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


            KeyInfo keyInfo = new KeyInfo();
            KeyInfoName kin = new KeyInfoName();
            kin.Value = _privateCertificate.Thumbprint;
            keyInfo.AddClause(kin);
            signedXml.KeyInfo = keyInfo;

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


            using (MemoryStream sout = new MemoryStream())
            {
              xmlDoc.Save(sout);
              sout.Position = 0;
              using (StreamReader reader = new StreamReader(sout))
              {
                string xmlOut = reader.ReadToEnd();
                return xmlOut;
              }
            }
          }

        }
Beispiel #11
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");
        }
Beispiel #12
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);
            }
        }
        private void OpprettReferanser(SignedXml signaturnode, IEnumerable<IAsiceAttachable> referanser)
        {
            foreach (var item in referanser)
            {
                signaturnode.AddReference(Sha256Referanse(item));
            }

            signaturnode.AddObject(
                new QualifyingPropertiesObject(
                    _sertifikat, "#Signature", referanser.ToArray(), _xml.DocumentElement)
                );

            signaturnode.AddReference(SignedPropertiesReferanse());
        }
Beispiel #15
0
        public static void SignDetachedResource(string inputFile, string outputSignatureXML, string certFile, String certPassword)
        {
            X509Certificate2 certxml = new X509Certificate2(certFile, certPassword);

            RSACryptoServiceProvider Key = (RSACryptoServiceProvider)certxml.PrivateKey;

            String XmlSigFileName = outputSignatureXML;

            // Sign the detached resourceand save the signature in an XML file.
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml();

            // Assign the key to the SignedXml object.
            signedXml.SigningKey = Key;

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

            // Add the passed Refrence to the reference object.
            reference.Uri = inputFile;

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

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(new RSAKeyValue((RSA)Key));
            if (certxml != null)
            {
                KeyInfoX509Data kinfox509 = new KeyInfoX509Data(certxml, X509IncludeOption.WholeChain);
                kinfox509.AddIssuerSerial(certxml.Issuer, certxml.SerialNumber);
                kinfox509.AddSubjectName(certxml.Subject);
                keyInfo.AddClause(kinfox509);
            }
            signedXml.KeyInfo = keyInfo;

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

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

            // Save the signed XML document to a file specified
            // using the passed string.
            XmlTextWriter xmltw = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false));
            xmlDigitalSignature.WriteTo(xmltw);
            xmltw.Close();
        }
Beispiel #16
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;
        }
    /// <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();
            }
        }
        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);
            }
        }
Beispiel #20
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);
    }
Beispiel #21
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();
            }
        }
Beispiel #22
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);
        }
        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);
        }
Beispiel #26
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;
        }
        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);
            }
        }
Beispiel #28
0
        private static void SignXml(XmlDocument Doc, RSA Key)
        {
            // Check arguments.
            if (Doc == null)
                throw new ArgumentException("Doc");
            if (Key == null)
                throw new ArgumentException("Key");

            SignedXml signedXml = new SignedXml(Doc);
            signedXml.SigningKey = Key;
            Reference reference = new Reference();
            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();
            Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));

        }
        /// <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);
        }
        /// <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;
        }
Beispiel #31
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;
        }