Exemplo n.º 1
0
        /// <summary>
        /// 对XML文件内容进行数字签名
        /// </summary>
        /// <param name="document">XML文档对象(输入参数)</param>
        /// <param name="key">RSA算法(输入参数)</param>
        public static void SignXml(XmlDocument document, RSA key)
        {
            // 参数验证
            if (document == null)
            {
                throw new ArgumentException("document");
            }
            if (key == null)
            {
                throw new ArgumentException("key");
            }

            SignedXml XML = new SignedXml(document);

            XML.SigningKey = key;
            System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference();
            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform transform = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(transform);
            XML.AddReference(reference);
            XML.ComputeSignature();
            XmlElement node = XML.GetXml();

            document.DocumentElement.AppendChild(document.ImportNode(node, true));
        }
        private static XmlDocument SignXmlDocument(XmlDocument xmlDocument, X509Certificate2 signingCertificate)
        {
            // Создание подписчика XML-документа
            var signedXml = new GostSignedXml(xmlDocument);

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

            // Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования
            var dataReference = new Reference { Uri = "#Id1", DigestMethod = GostSignedXml.XmlDsigGost3411Url };

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

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

            // Установка информации о сертификате, который использовался для создания подписи
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoX509Data(signingCertificate));
            signedXml.KeyInfo = keyInfo;

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

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

            // Добавление подписи в исходный документ
            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signatureXml, true));

            return xmlDocument;
        }
Exemplo n.º 3
0
        public string GetSignedXml(string xmlDocument, X509Certificate2 cert)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xmlDocument);

            SignedXml signedXml = new SignedXml(doc)
            {
                SigningKey = cert.PrivateKey
            };

            System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.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));

            var response = xmlSerializer.Deserialize <SSOLibrary.Signature>(xmlDigitalSignature.OuterXml);

            signableObject.Signature = response;
            var signedRequest = this.xmlSerializer.Serialize(signableObject.GetType(), signableObject);

            return(signedRequest);
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
        private void AddReference(string id, Stream contents)
        {
            var reference = new System.Security.Cryptography.Xml.Reference(contents);

            reference.Uri          = id;
            reference.DigestMethod = AlgorithmSuite.DefaultDigestAlgorithm;
            reference.AddTransform(new XmlDsigExcC14NTransform());
            _signedXml.AddReference(reference);
        }
Exemplo n.º 6
0
 protected static void SetAttachmentTransformContentType(Reference reference, Attachment attachment)
 {
     foreach (object transform in reference.TransformChain)
     {
         if (transform is AttachmentSignatureTransform attachmentTransform)
         {
             attachmentTransform.ContentType = attachment.ContentType;
         }
     }
 }
Exemplo n.º 7
0
        private Reference getReference(XmlNode mainNode)
        {
            Reference reference = new Reference();

              string mainNodeID = mainNode.Attributes["Id"].InnerText;
              reference.Uri = "#" + mainNodeID;
              reference.DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256";
              reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

              return reference;
        }
Exemplo n.º 8
0
        private void AddXmlReference(string id, string hashFunction)
        {
            var reference = new Reference("#" + id)
            {
                DigestMethod = hashFunction
            };
            Transform transform = new XmlDsigExcC14NTransform();

            reference.AddTransform(transform);
            base.AddReference(reference);
        }
Exemplo n.º 9
0
        private void AddSignatureReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer)
        {
            // No transforms added to Reference as the digest value has already been calculated
            byte[] hashValue;
            headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out hashValue);
            var reference = new System.Security.Cryptography.Xml.Reference();

            reference.DigestMethod = AlgorithmSuite.DefaultDigestAlgorithm;
            reference.DigestValue  = hashValue;
            reference.Id           = headerId;
            _signedXml.AddReference(reference);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Resets the reference stream position to 0.
        /// </summary>
        /// <param name="reference"></param>
        protected static void ResetReferenceStreamPosition(Reference reference)
        {
            if (RefTargetField == null)
            {
                return;
            }

            if (RefTargetField.GetValue(reference) is Stream referenceStream)
            {
                StreamUtilities.MovePositionToStreamStart(referenceStream);
            }
        }
Exemplo n.º 11
0
        public static Signature ObterAssinatura <T>(T objeto, string id, X509Certificate2 certificadoDigital,
                                                    string signatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
                                                    string digestMethod    = "http://www.w3.org/2000/09/xmldsig#sha1") where T : class
        {
            if (id == null)
            {
                throw new Exception("Não é possível assinar um objeto evento sem sua respectiva Id!");
            }

            var documento = new XmlDocument {
                PreserveWhitespace = true
            };

            var xml = XmlUtils.ClasseParaXmlString(objeto);

            documento.LoadXml(xml);

            var docXml = new SignedXml(documento)
            {
                SigningKey = certificadoDigital.PrivateKey
            };

            docXml.SignedInfo.SignatureMethod = signatureMethod;

            var reference = new Reference {
                Uri = "#" + id, DigestMethod = digestMethod
            };

            var envelopedSigntature = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(envelopedSigntature);

            var c14Transform = new XmlDsigC14NTransform();

            reference.AddTransform(c14Transform);

            docXml.AddReference(reference);

            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(certificadoDigital));

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

            var xmlDigitalSignature = docXml.GetXml();
            var assinatura          = XmlUtils.XmlStringParaClasse <Signature>(xmlDigitalSignature.OuterXml);

            return(assinatura);
        }
Exemplo n.º 12
0
        private byte[] GetReferenceHash(System.Security.Cryptography.Xml.Reference r)
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            if (r.Uri == "")
            {
                doc = envdoc;
            }
            else
            {
                XmlElement element = GetIdElement(envdoc, r.Uri != null ? r.Uri.Remove(0, 1) : null);
                doc.LoadXml(element.OuterXml);

                if (r.TransformChain.Count > 0)
                {
                    var namespaces = GetAllNamespaces(element);

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

            Stream s = null;

            if (r.TransformChain.Count > 0)
            {
                foreach (System.Security.Cryptography.Xml.Transform t in r.TransformChain)
                {
                    if (s == null)
                    {
                        s = ApplyTransform(t, doc);
                    }
                    else
                    {
                        s = ApplyTransform(t, s);
                    }
                }
            }
            else
            {
                s = ApplyTransform(new System.Security.Cryptography.Xml.XmlDsigC14NTransform(), doc);
            }

            HashAlgorithm hash = (HashAlgorithm)CryptoConfig.CreateFromName(r.DigestMethod);

            return(hash.ComputeHash(s));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Add Cid Attachment Reference
        /// </summary>
        /// <param name="attachment"></param>
        /// <param name="digestMethod"></param>
        private void AddAttachmentReference(Attachment attachment, string digestMethod)
        {
            var attachmentReference = new Reference(uri: CidPrefix + attachment.Id)
            {
                DigestMethod = digestMethod
            };

            attachmentReference.AddTransform(new AttachmentSignatureTransform());
            base.AddReference(attachmentReference);

            SetReferenceStream(attachmentReference, attachment);
            SetAttachmentTransformContentType(attachmentReference, attachment);
            ResetReferenceStreamPosition(attachmentReference);
        }
        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();
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Sets the stream of a SignedInfo reference.
        /// </summary>
        /// <param name="reference"></param>
        /// <param name="attachment"></param>
        protected static void SetReferenceStream(Reference reference, Attachment attachment)
        {
            // We need reflection to set these 2 types. They are implicitly set to Xml references,
            // but this causes problems with cid: references, since they're not part of the original stream.
            // If performance is slow on this, we can investigate the Delegate.CreateDelegate method to speed things up,
            // however keep in mind that the reference object changes with every call, so we can't just keep the same delegate and call that.

            if (RefTargetTypeField != null)
            {
                const int streamReferenceTargetType = 0;
                RefTargetTypeField.SetValue(reference, streamReferenceTargetType);
            }

            if (RefTargetField != null)
            {
                RefTargetField.SetValue(reference, new NonCloseableStream(attachment.Content));
            }
        }
Exemplo n.º 16
0
        public void ComputeSignature(X509Certificate2 certificate, X509IncludeOption includeOption, string id)
        {
            SigningKey = (RSACryptoServiceProvider)certificate.PrivateKey;

            SignedInfo.CanonicalizationMethod = Saml2SignedXml.XmlDsigExcC14NTransformUrl;
            //SignedInfo.SignatureMethod = SecurityAlgorithms.RsaSha256Signature;

            var reference = new Reference("#" + id);
            // reference.DigestMethod = SecurityAlgorithms.Sha1Digest;
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

            AddReference(reference);
            ComputeSignature();

            KeyInfo = new KeyInfo();
            KeyInfo.AddClause(new KeyInfoX509Data(certificate, includeOption));
        }
Exemplo n.º 17
0
        private static XmlElement GerarAssinatura(XmlDocument doc, string infoElement, string signAtribute,
                                                  X509Certificate2 certificado, bool comments = false, SignDigest digest = SignDigest.SHA1)
        {
            Guard.Against <ArgumentException>(!infoElement.IsEmpty() && doc.GetElementsByTagName(infoElement).Count != 1, "Referencia invalida ou não é unica.");

            //Adiciona Certificado ao Key Info
            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(certificado));

            //Seta chaves
            var signedDocument = new SignedXml(doc)
            {
                SigningKey = certificado.PrivateKey,
                KeyInfo    = keyInfo,
                SignedInfo =
                {
                    SignatureMethod = GetSignatureMethod(digest)
                }
            };

            var uri = infoElement.IsEmpty() || signAtribute.IsEmpty() ? "" :
                      $"#{doc.GetElementsByTagName(infoElement)[0].Attributes?[signAtribute]?.InnerText}";

            // Cria referencia
            var reference = new Reference
            {
                Uri          = uri,
                DigestMethod = GetDigestMethod(digest)
            };

            // Adiciona transformação a referencia
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigC14NTransform(comments));

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

            // Calcula Assinatura
            signedDocument.ComputeSignature();

            // Pega representação da assinatura
            return(signedDocument.GetXml());
        }
Exemplo n.º 18
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());
        }
Exemplo n.º 20
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);
        }
        public static XmlElement CreateSignature(XmlDocument document, X509Certificate2 certificate, string referenceId, string referenceValue)
        {
            var samlSignedXml = new SamlSignedXml(document, referenceId);
            // Add the key to the SignedXml xmlDocument.
            samlSignedXml.SigningKey = certificate.PrivateKey;

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

            reference.Uri = string.Empty;
            reference.Uri = "#" + referenceValue;

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

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

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

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

            keyInfo.AddClause(keyData);

            samlSignedXml.KeyInfo = keyInfo;

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

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

            return xmlDigitalSignature;
        }
        /// <summary>
        /// Creates a <see cref="Reference"/> model from a <see cref="System.Security.Cryptography.Xml.Reference"/> element.
        /// </summary>
        /// <param name="refElement"></param>
        /// <returns></returns>
        public static Reference CreateFromReferenceElement(System.Security.Cryptography.Xml.Reference refElement)
        {
            if (refElement == null)
            {
                throw new ArgumentNullException(nameof(refElement));
            }

            IEnumerable <ReferenceTransform> CreateTransformsFromChain(TransformChain chain)
            {
                if (chain != null)
                {
                    foreach (Transform transform in chain)
                    {
                        yield return(new ReferenceTransform(transform.Algorithm));
                    }
                }
            }

            return(new Reference(
                       refElement.Uri,
                       CreateTransformsFromChain(refElement.TransformChain),
                       new ReferenceDigestMethod(refElement.DigestMethod),
                       refElement.DigestValue));
        }
Exemplo n.º 23
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // SignedInfo
            XmlElement signedInfoElement = value;

            if (!signedInfoElement.LocalName.Equals("SignedInfo"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // Id attribute -- optional
            m_id = Utils.GetAttribute(signedInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            // CanonicalizationMethod -- must be present
            XmlElement canonicalizationMethodElement = signedInfoElement.SelectSingleNode("ds:CanonicalizationMethod", nsm) as XmlElement;

            if (canonicalizationMethodElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/CanonicalizationMethod");
            }
            m_canonicalizationMethod          = Utils.GetAttribute(canonicalizationMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
            m_canonicalizationMethodTransform = null;
            if (canonicalizationMethodElement.ChildNodes.Count > 0)
            {
                this.CanonicalizationMethodObject.LoadInnerXml(canonicalizationMethodElement.ChildNodes);
            }

            // SignatureMethod -- must be present
            XmlElement signatureMethodElement = signedInfoElement.SelectSingleNode("ds:SignatureMethod", nsm) as XmlElement;

            if (signatureMethodElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureMethod");
            }
            m_signatureMethod = Utils.GetAttribute(signatureMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);

            // Now get the output length if we are using a MAC algorithm
            XmlElement signatureLengthElement = signatureMethodElement.SelectSingleNode("ds:HMACOutputLength", nsm) as XmlElement;

            if (signatureLengthElement != null)
            {
                m_signatureLength = signatureLengthElement.InnerXml;
            }

            // flush out any reference that was there
            m_references.Clear();

            XmlNodeList referenceNodes = signedInfoElement.SelectNodes("ds:Reference", nsm);

            if (referenceNodes != null)
            {
                foreach (XmlNode node in referenceNodes)
                {
                    XmlElement referenceElement = node as XmlElement;
                    Reference  reference        = new Reference();
                    AddReference(reference);
                    reference.LoadXml(referenceElement);
                }
            }

            // Save away the cached value
            m_cachedXml = signedInfoElement;
        }
Exemplo n.º 24
0
        private SoapFilterResult Sign(SoapEnvelope envelope)
        {
            XmlNode securityNode = envelope.CreateNode(XmlNodeType.Element, "wsse:Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            envelope.PreserveWhitespace = false;

            /*
             * <wsu:Timestamp wsu:Id="Timestamp-10ba255c-ea41-4041-ab07-2b7a3220ef88">
             * <wsu:Created>2011-01-07T07:49:08Z</wsu:Created>
             * <wsu:Expires>2011-01-07T07:54:08Z</wsu:Expires>
             * </wsu:Timestamp>
             */
            XmlNode timestampNode = envelope.CreateNode(
                XmlNodeType.Element,
                "wsu:Timestamp", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            XmlElement timestampElement = timestampNode as XmlElement;

            XmlAttribute IdAttTs = envelope.CreateAttribute("wsu", "Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            IdAttTs.Value = "Timestamp-" + Guid.NewGuid().ToString();

            XmlNode created = envelope.CreateNode(XmlNodeType.Element, "wsu:Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            created.InnerText = DateTime.Now.ToUniversalTime().ToString("o");

            DateTime expiration = DateTime.Now.AddMinutes(5);
            XmlNode  expires    = envelope.CreateNode(XmlNodeType.Element, "wsu:Expires", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            expires.InnerText = expiration.ToUniversalTime().ToString("o");

            timestampElement.Attributes.Append(IdAttTs);
            timestampElement.AppendChild(created);
            timestampElement.AppendChild(expires);

            XmlNode binarySecurityTokenNode = envelope.CreateNode(
                XmlNodeType.Element,
                "wsse:BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            XmlElement binarySecurityTokenElement = binarySecurityTokenNode as XmlElement;

            binarySecurityTokenElement.SetAttribute(
                "xmlns:wsu",
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            binarySecurityTokenElement.SetAttribute(
                "EncodingType",
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
            binarySecurityTokenElement.SetAttribute(
                "ValueType",
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");

            XmlAttribute IdAtt = envelope.CreateAttribute("wsu", "Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            IdAtt.Value = _parentAssertion.Token.Id;
            binarySecurityTokenElement.Attributes.Append(IdAtt);

            byte[] publicCert = _parentAssertion.Token.Certificate.GetRawCertData();
            binarySecurityTokenElement.InnerXml = Convert.ToBase64String(publicCert, Base64FormattingOptions.None);

            SignatureFramework.SignedXml signature = new SignatureFramework.SignedXml(envelope);
            signature.Signature.Id = "Signature-" + Guid.NewGuid().ToString();

            KeyInfo ki = new KeyInfo();

            ki.Id = "KeyInfo-" + Guid.NewGuid().ToString();
            SecurityTokenReference sectokenReference = new SecurityTokenReference(_parentAssertion.Token, SecurityTokenReference.SerializationOptions.Reference);

            ki.AddClause(sectokenReference);

            signature.KeyInfo = ki;

            SignatureFramework.SignedInfo si = new SignatureFramework.SignedInfo();

            si.SignatureMethod = _parentAssertion.SignatureMethod;

            si.CanonicalizationMethod = SignatureFramework.XmlSignatureConstants.XmlDsigExcC14NTransformUrl;

            String bodyId = "Body-" + Guid.NewGuid().ToString();

            envelope.Body.SetAttribute("Id", bodyId);

            System.Security.Cryptography.Xml.Reference bsBody = new System.Security.Cryptography.Xml.Reference();
            bsBody.Uri = "#" + bodyId;
            bsBody.AddTransform(new System.Security.Cryptography.Xml.XmlDsigExcC14NTransform());
            si.AddReference(bsBody);

            System.Security.Cryptography.Xml.Reference refTimestamp = new System.Security.Cryptography.Xml.Reference();
            refTimestamp.Uri = "#" + IdAttTs.Value;
            refTimestamp.AddTransform(new System.Security.Cryptography.Xml.XmlDsigExcC14NTransform());
            si.AddReference(refTimestamp);

            signature.SignedInfo = si;

            bool disposeCryptoProvider = false;

            var key = (RSACryptoServiceProvider)_parentAssertion.Token.Certificate.PrivateKey;

            if (key.CspKeyContainerInfo.ProviderName == "Microsoft Strong Cryptographic Provider" ||
                key.CspKeyContainerInfo.ProviderName == "Microsoft Enhanced Cryptographic Provider v1.0" ||
                key.CspKeyContainerInfo.ProviderName == "Microsoft Base Cryptographic Provider v1.0" ||
                key.CspKeyContainerInfo.ProviderName == "Microsoft RSA SChannel Cryptographic Provider")
            {
                Type CspKeyContainerInfo_Type = typeof(CspKeyContainerInfo);

                FieldInfo     CspKeyContainerInfo_m_parameters = CspKeyContainerInfo_Type.GetField("m_parameters", BindingFlags.NonPublic | BindingFlags.Instance);
                CspParameters parameters = (CspParameters)CspKeyContainerInfo_m_parameters.GetValue(key.CspKeyContainerInfo);

                var cspparams = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider", key.CspKeyContainerInfo.KeyContainerName);
                cspparams.KeyNumber  = parameters.KeyNumber;
                cspparams.Flags      = parameters.Flags;
                signature.SigningKey = new RSACryptoServiceProvider(cspparams);

                disposeCryptoProvider = true;
            }
            else
            {
                signature.SigningKey = _parentAssertion.Token.Certificate.PrivateKey;
            }

            securityNode.AppendChild(binarySecurityTokenNode);
            securityNode.AppendChild(timestampNode);
            envelope.ImportNode(securityNode, true);
            XmlNode node = envelope.Header;

            node.AppendChild(securityNode);

            signature.ComputeSignature();
            securityNode.AppendChild(envelope.ImportNode(signature.GetXml(), true));

            if (disposeCryptoProvider)
            {
                signature.SigningKey.Dispose();
            }

            return(SoapFilterResult.Continue);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Signs the document given as an argument.
        /// </summary>
        /// <param name="doc">The doc.</param>
        private static void SignDocument(XmlDocument doc)
        {
            var signedXml = new SignedXml(doc);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // TODO Dynamically dig out the correct ID attribute from the XmlDocument.
            var reference = new Reference("#_b8977dc86cda41493fba68b32ae9291d");

            var 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());
            var 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.
            var cert = new X509Certificate2(@"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();

            var nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.Assertion);
            Assert.That(nodes.Count == 1);
            var node = nodes[0];
            doc.DocumentElement.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), node);
        }
Exemplo n.º 26
0
        private byte[] GetReferenceHash(Reference r, bool check_hmac)
        {
            Stream      s   = null;
            XmlDocument doc = null;

            if (r.Uri == String.Empty)
            {
                doc = envdoc;
            }
            else if (r.Type == XmlSignature.Uri.Manifest)
            {
                doc = GetManifest(r);
            }
            else
            {
                doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                string objectName = null;

                if (r.Uri.StartsWith("#xpointer"))
                {
                    string uri = string.Join("", r.Uri.Substring(9).Split(whitespaceChars));
                    if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
                    {
                        // FIXME: how to handle invalid xpointer?
                        uri = String.Empty;
                    }
                    else
                    {
                        uri = uri.Substring(1, uri.Length - 2);
                    }
                    if (uri == "/")
                    {
                        doc = envdoc;
                    }
                    else if (uri.Length > 6 && uri.StartsWith("id(") && uri [uri.Length - 1] == ')')
                    {
                        // id('foo'), id("foo")
                        objectName = uri.Substring(4, uri.Length - 6);
                    }
                }
                else if (r.Uri [0] == '#')
                {
                    objectName = r.Uri.Substring(1);
                }
                else if (xmlResolver != null)
                {
                    // TODO: test but doc says that Resolver = null -> no access
                    try {
                        // no way to know if valid without throwing an exception
                        Uri uri = new Uri(r.Uri);
                        s = (Stream)xmlResolver.GetEntity(uri, null, typeof(Stream));
                    }
                    catch {
                        // may still be a local file (and maybe not xml)
                        s = File.OpenRead(r.Uri);
                    }
                }
                if (objectName != null)
                {
                    XmlElement found = null;
                    foreach (DataObject obj in m_signature.ObjectList)
                    {
                        if (obj.Id == objectName)
                        {
                            found = obj.GetXml();
                            found.SetAttribute("xmlns", SignedXml.XmlDsigNamespaceUrl);
                            doc.AppendChild(doc.ImportNode(found, true));
                            // FIXME: there should be theoretical justification of copying namespace declaration nodes this way.
                            foreach (XmlNode n in found.ChildNodes)
                            {
                                // Do not copy default namespace as it must be xmldsig namespace for "Object" element.
                                if (n.NodeType == XmlNodeType.Element)
                                {
                                    FixupNamespaceNodes(n as XmlElement, doc.DocumentElement, true);
                                }
                            }
                            break;
                        }
                    }
                    if (found == null && envdoc != null)
                    {
                        found = GetIdElement(envdoc, objectName);
                        if (found != null)
                        {
                            doc.AppendChild(doc.ImportNode(found, true));
                            FixupNamespaceNodes(found, doc.DocumentElement, false);
                        }
                    }
                    if (found == null)
                    {
                        throw new CryptographicException(String.Format("Malformed reference object: {0}", objectName));
                    }
                }
            }

            if (r.TransformChain.Count > 0)
            {
                foreach (Transform t in r.TransformChain)
                {
                    if (s == null)
                    {
                        s = ApplyTransform(t, doc);
                    }
                    else
                    {
                        t.LoadInput(s);
                        object o = t.GetOutput();
                        if (o is Stream)
                        {
                            s = (Stream)o;
                        }
                        else
                        {
                            s = CanonicalizeOutput(o);
                        }
                    }
                }
            }
            else if (s == null)
            {
                // we must not C14N references from outside the document
                // e.g. non-xml documents
                if (r.Uri [0] != '#')
                {
                    s = new MemoryStream();
                    doc.Save(s);
                }
                else
                {
                    // apply default C14N transformation
                    s = ApplyTransform(new XmlDsigC14NTransform(), doc);
                }
            }
            HashAlgorithm digest = GetHash(r.DigestMethod, check_hmac);

            return((digest == null) ? null : digest.ComputeHash(s));
        }
Exemplo n.º 27
0
        protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(
            SendSecurityHeaderElement[] signatureConfirmations,
            SecurityToken[] signedEndorsingTokens,
            SecurityToken[] signedTokens,
            SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature)
        {
            if (_signedXml == null)
            {
                return(null);
            }

            SecurityTimestamp timestamp = Timestamp;

            if (timestamp != null)
            {
                if (timestamp.Id == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.TimestampToSignHasNoId));
                }

                var buffer = new byte[64];
                var ms     = new MemoryStream();
                StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(
                    ms, timestamp, buffer);
                ms.Position = 0;
                AddReference("#" + timestamp.Id, ms);
                var reference = new System.Security.Cryptography.Xml.Reference(ms);
            }

            if ((ShouldSignToHeader) && (_signingKey != null || _signedXml.SigningKey != null) && (Version.Addressing != AddressingVersion.None))
            {
                if (_toHeaderStream != null)
                {
                    AddReference("#" + _toHeaderId, _toHeaderStream);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.TransportSecurityRequireToHeader));
                }
            }

            AddSignatureReference(signatureConfirmations);
            if (isPrimarySignature && ShouldProtectTokens)
            {
                AddPrimaryTokenSignatureReference(ElementContainer.SourceSigningToken, SigningTokenParameters);
            }

            if (RequireMessageProtection)
            {
                throw new PlatformNotSupportedException(nameof(RequireMessageProtection));
            }

            if (_signedXml.SignedInfo.References.Count == 0)
            {
                throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.NoPartsOfMessageMatchedPartsToSign), Message);
            }
            try
            {
                if (_signingKey != null)
                {
                    _signedXml.ComputeSignature(_signingKey);
                }
                else
                {
                    _signedXml.ComputeSignature();
                }

                return(new SignatureValue(_signedXml.Signature));
            }
            finally
            {
                _hashStream = null;
                _signingKey = null;
                _signedXml  = null;
                _effectiveSignatureParts = null;
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Añade un objeto de tipo <code>Reference</code>
 /// </summary>
 /// <param name="reference"></param>
 public void AddReference(System.Security.Cryptography.Xml.Reference reference)
 {
     signature.SignedInfo.AddReference(reference);
 }
Exemplo n.º 29
0
        public static void SignXmlFile(string fileName, ref string signedContent, RSA key)
        {
            // Check the arguments.
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (signedContent == null)
            {
                throw new ArgumentNullException("signedFileName");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            // 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.
            //doc.Load(new XmlTextReader(FileName));
            doc.LoadXml(fileName);
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = key;
            // Get the signature object from the SignedXml object.
            System.Security.Cryptography.Xml.Signature XMLSignature = signedXml.Signature;
            // Create a reference to be signed.  Pass ""
            // to specify that all of the current XML
            // document should be signed.
            System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference("");
            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            // Add the Reference object to the Signature object.
            XMLSignature.SignedInfo.AddReference(reference);
            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            System.Security.Cryptography.Xml.KeyInfo keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
            keyInfo.AddClause(new RSAKeyValue((RSA)key));
            // Add the KeyInfo object to the Reference object.
            XMLSignature.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();

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

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

            signedContent = doc.InnerXml;
        }
Exemplo n.º 30
0
		public void AddReference (Reference reference) 
		{
			references.Add (reference);
		}
Exemplo n.º 31
0
		private XmlDocument GetManifest (Reference r) 
		{
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;

			if (r.Uri [0] == '#') {
				// local manifest
				if (signatureElement != null) {
					XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
					if (xel == null)
						throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
					doc.AppendChild (doc.ImportNode (xel, true));
					FixupNamespaceNodes (xel, doc.DocumentElement, false);
				}
			}
			else if (xmlResolver != null) {
				// TODO: need testing
				Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
				doc.Load (s);
			}

			if (doc.FirstChild != null) {
				// keep a copy of the manifests to check their references later
				if (manifests == null)
					manifests = new ArrayList ();
				manifests.Add (doc);

				return doc;
			}
			return null;
		}
Exemplo n.º 32
0
        //public static string RetornarXmlFirmado(string xmlString, string rutaCertificado, string claveCertificado, out string hash)
        //{
        //    hash = null;

        //    XmlDocument documentXml = new XmlDocument();

        //    documentXml.PreserveWhitespace = true;
        //    documentXml.LoadXml(xmlString);
        //    var nodoExtension = documentXml.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(0);

        //    if (nodoExtension == null)
        //    {
        //        throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
        //    }

        //    nodoExtension.RemoveAll();

        //    SignedXml firmado = new SignedXml(documentXml);

        //    var xmlSignature = firmado.Signature;

        //    byte[] certificadoByte = File.ReadAllBytes(rutaCertificado);
        //    X509Certificate2 certificado = new X509Certificate2();
        //    //certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        //    certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.Exportable);
        //    firmado.SigningKey = certificado.GetRSAPrivateKey();
        //    //firmado.SigningKey = (RSA)certificado.PrivateKey;
        //    //firmado.SigningKey = certificado.PrivateKey;

        //    //digest info agregada en la seccion firma
        //    var env = new XmlDsigEnvelopedSignatureTransform();
        //    Reference reference = new Reference();
        //    reference.AddTransform(env);

        //    reference.Uri = "";
        //    firmado.AddReference(reference);
        //    firmado.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        //    reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        //    var keyInfoData = new KeyInfoX509Data(certificado);
        //    keyInfoData.AddSubjectName(certificado.Subject);

        //    // info para la llave publica
        //    KeyInfo keyInfo = new KeyInfo();
        //    keyInfo.AddClause(keyInfoData);
        //    //keyInfo.sub

        //    xmlSignature.KeyInfo = keyInfo;
        //    xmlSignature.Id = "signatureKG";
        //    firmado.ComputeSignature();


        //    // Recuperamos el valor Hash de la firma para este documento.
        //    if (reference.DigestValue != null)
        //    {
        //        hash = Convert.ToBase64String(reference.DigestValue);
        //    }

        //    XmlNode xmlNodeFirmado = firmado.GetXml();
        //    xmlNodeFirmado.Prefix = "ds";

        //    //XmlNode xmlNodeContent = documentXml.CreateElement("ext", "ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
        //    //xmlNodeContent.AppendChild(xmlNodeFirmado);

        //    //XmlNode xmlNode = documentXml.CreateElement("ext", "UBLExtension", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
        //    //xmlNode.AppendChild(xmlNodeContent);

        //    nodoExtension.AppendChild(xmlNodeFirmado);

        //    var settings = new XmlWriterSettings()
        //    {
        //        Encoding = Encoding.UTF8,
        //        Indent = true,
        //        IndentChars = "\t",
        //        NewLineChars = Environment.NewLine

        //    };

        //    string resultado = String.Empty;
        //    using (var memDoc = new MemoryStream())
        //    {

        //        using (var writer = XmlWriter.Create(memDoc, settings))
        //        {
        //            //XDocument xDocument = XDocument.Parse(documentXml.OuterXml);
        //            //xDocument.WriteTo(writer);
        //            documentXml.WriteTo(writer);
        //        }

        //        //resultado = Encoding.Unicode.GetString(memDoc.ToArray());
        //        //resultado = Encoding.GetEncoding("ISO-8859-1").GetString(memDoc.ToArray());
        //        //resultado = Convert.ToBase64String(memDoc.ToArray());
        //        resultado = Encoding.UTF8.GetString(memDoc.ToArray());

        //    }
        //    return resultado;
        //}

        public static string RetornarXmlFirmado(string prefijoComprobanteBusqueda, string tnsString, string xmlString, string rutaCertificado, string claveCertificado, out string hash)
        {
            hash = null;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.LoadXml(xmlString);

            X509Certificate2 certificado = new X509Certificate2(rutaCertificado, claveCertificado);

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable);

            nsMgr.AddNamespace("tns", tnsString);
            nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");

            XmlElement elem = xmlDocument.CreateElement("ext:ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");

            xmlDocument.SelectSingleNode($"{prefijoComprobanteBusqueda}/ext:UBLExtensions/ext:UBLExtension", nsMgr).AppendChild(elem);

            SignedXml signedXml = new SignedXml(xmlDocument);

            signedXml.SigningKey = certificado.GetRSAPrivateKey();
            System.Security.Cryptography.Xml.KeyInfo KeyInfo = new System.Security.Cryptography.Xml.KeyInfo();

            System.Security.Cryptography.Xml.Reference Reference = new System.Security.Cryptography.Xml.Reference();
            Reference.Uri = "";

            Reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(Reference);

            X509Chain X509Chain = new X509Chain();

            X509Chain.Build(certificado);

            X509ChainElement local_element = X509Chain.ChainElements[0];
            KeyInfoX509Data  x509Data      = new KeyInfoX509Data(local_element.Certificate);

            string subjectName = local_element.Certificate.Subject;

            x509Data.AddSubjectName(subjectName);
            KeyInfo.AddClause(x509Data);
            signedXml.Signature.Id = "signatureKG";
            signedXml.KeyInfo      = KeyInfo;
            signedXml.ComputeSignature();
            XmlElement signature = signedXml.GetXml();
            XmlNode    dg        = signature.GetElementsByTagName("DigestValue", "http://www.w3.org/2000/09/xmldsig#")[0];
            XmlNode    sg        = signature.GetElementsByTagName("SignatureValue", "http://www.w3.org/2000/09/xmldsig#")[0];

            hash = dg.InnerText;
            //SignatureValue = sg.InnerText;

            signature.Prefix = "ds";
            //SetPrefix("ds", signature);

            elem.AppendChild(signature);

            MemoryStream msXMLFirmado = new MemoryStream();

            xmlDocument.Save(msXMLFirmado);

            //msXMLFirmado.Position = 1;

            return(Encoding.UTF8.GetString(msXMLFirmado.ToArray()).Substring(1));
        }
Exemplo n.º 33
0
		public void LoadXml (XmlElement value) 
		{
			if (value == null)
				throw new ArgumentNullException ("value");

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

			id = GetAttribute (value, XmlSignature.AttributeNames.Id);

			for (int i = 0; i < value.ChildNodes.Count; i++) {
				XmlNode n = value.ChildNodes [i];
				if (n.NodeType == XmlNodeType.Element &&
					n.LocalName == XmlSignature.ElementNames.Reference &&
					n.NamespaceURI == XmlSignature.NamespaceURI) {
					Reference r = new Reference ();
					r.LoadXml ((XmlElement) n);
					AddReference (r);
				}
			}
			element = value;
		}
Exemplo n.º 34
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            // SignedInfo
            XmlElement signedInfoElement = value;

            if (!signedInfoElement.LocalName.Equals("SignedInfo"))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo");
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            int expectedChildNodes = 0;

            // Id attribute -- optional
            _id = Utils.GetAttribute(signedInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl);
            if (!Utils.VerifyAttributes(signedInfoElement, "Id"))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo");
            }

            // CanonicalizationMethod -- must be present
            XmlNodeList canonicalizationMethodNodes = signedInfoElement.SelectNodes("ds:CanonicalizationMethod", nsm);

            if (canonicalizationMethodNodes == null || canonicalizationMethodNodes.Count == 0 || canonicalizationMethodNodes.Count > 1)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/CanonicalizationMethod");
            }
            XmlElement canonicalizationMethodElement = canonicalizationMethodNodes.Item(0) as XmlElement;

            expectedChildNodes     += canonicalizationMethodNodes.Count;
            _canonicalizationMethod = Utils.GetAttribute(canonicalizationMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
            if (_canonicalizationMethod == null || !Utils.VerifyAttributes(canonicalizationMethodElement, "Algorithm"))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/CanonicalizationMethod");
            }
            _canonicalizationMethodTransform = null;
            if (canonicalizationMethodElement.ChildNodes.Count > 0)
            {
                CanonicalizationMethodObject.LoadInnerXml(canonicalizationMethodElement.ChildNodes);
            }

            // SignatureMethod -- must be present
            XmlNodeList signatureMethodNodes = signedInfoElement.SelectNodes("ds:SignatureMethod", nsm);

            if (signatureMethodNodes == null || signatureMethodNodes.Count == 0 || signatureMethodNodes.Count > 1)
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/SignatureMethod");
            }
            XmlElement signatureMethodElement = signatureMethodNodes.Item(0) as XmlElement;

            expectedChildNodes += signatureMethodNodes.Count;
            _signatureMethod    = Utils.GetAttribute(signatureMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
            if (_signatureMethod == null || !Utils.VerifyAttributes(signatureMethodElement, "Algorithm"))
            {
                throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/SignatureMethod");
            }

            // Now get the output length if we are using a MAC algorithm
            XmlElement signatureLengthElement = signatureMethodElement.SelectSingleNode("ds:HMACOutputLength", nsm) as XmlElement;

            if (signatureLengthElement != null)
            {
                _signatureLength = signatureLengthElement.InnerXml;
            }

            // flush out any reference that was there
            _references.Clear();

            // Reference - 0 or more
            XmlNodeList referenceNodes = signedInfoElement.SelectNodes("ds:Reference", nsm);

            if (referenceNodes != null)
            {
                if (referenceNodes.Count > Utils.MaxReferencesPerSignedInfo)
                {
                    throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/Reference");
                }
                foreach (XmlNode node in referenceNodes)
                {
                    XmlElement referenceElement = node as XmlElement;
                    Reference  reference        = new Reference();
                    AddReference(reference);
                    reference.LoadXml(referenceElement);
                }
                expectedChildNodes += referenceNodes.Count;
                // Verify that there aren't any extra nodes that aren't allowed
                if (signedInfoElement.SelectNodes("*").Count != expectedChildNodes)
                {
                    throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo");
                }
            }

            // Save away the cached value
            _cachedXml = signedInfoElement;
        }
Exemplo n.º 35
0
		public void LoadXml (XmlElement value) 
		{
			if (value == null)
				throw new ArgumentNullException ("value");

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

			id = GetAttribute (value, XmlSignature.AttributeNames.Id);
			c14nMethod = XmlSignature.GetAttributeFromElement (value, XmlSignature.AttributeNames.Algorithm, XmlSignature.ElementNames.CanonicalizationMethod);

			XmlElement sm = XmlSignature.GetChildElement (value, XmlSignature.ElementNames.SignatureMethod, XmlSignature.NamespaceURI);
			if (sm != null) {
				signatureMethod = sm.GetAttribute (XmlSignature.AttributeNames.Algorithm);
				XmlElement length = XmlSignature.GetChildElement (sm, XmlSignature.ElementNames.HMACOutputLength, XmlSignature.NamespaceURI);
				if (length != null) {
					signatureLength = length.InnerText;
				}
			}

			for (int i = 0; i < value.ChildNodes.Count; i++) {
				XmlNode n = value.ChildNodes [i];
				if (n.NodeType == XmlNodeType.Element &&
					n.LocalName == XmlSignature.ElementNames.Reference &&
					n.NamespaceURI == XmlSignature.NamespaceURI) {
					Reference r = new Reference ();
					r.LoadXml ((XmlElement) n);
					AddReference (r);
				}
			}
			element = value;
		}
Exemplo n.º 36
0
		public void AddReference (Reference reference) 
		{
			if (reference == null)
				throw new ArgumentNullException ("reference");
			m_signature.SignedInfo.AddReference (reference);
		}
Exemplo n.º 37
0
        //
        // public methods
        //

        public void AddReference(Reference reference)
        {
            m_signature.SignedInfo.AddReference(reference);
        }
Exemplo n.º 38
0
		private byte[] GetReferenceHash (Reference r, bool check_hmac) 
		{
			Stream s = null;
			XmlDocument doc = null;
			if (r.Uri == String.Empty) {
				doc = envdoc;
			}
			else if (r.Type == XmlSignature.Uri.Manifest) {
				doc = GetManifest (r);
			}
			else {
				doc = new XmlDocument ();
				doc.PreserveWhitespace = true;
				string objectName = null;

				if (r.Uri.StartsWith ("#xpointer")) {
					string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
					if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
						// FIXME: how to handle invalid xpointer?
						uri = String.Empty;
					else
						uri = uri.Substring (1, uri.Length - 2);
					if (uri == "/")
						doc = envdoc;
					else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
						// id('foo'), id("foo")
						objectName = uri.Substring (4, uri.Length - 6);
				}
				else if (r.Uri [0] == '#') {
					objectName = r.Uri.Substring (1);
				}
				else if (xmlResolver != null) {
					// TODO: test but doc says that Resolver = null -> no access
					try {
						// no way to know if valid without throwing an exception
						Uri uri = new Uri (r.Uri);
						s = (Stream) xmlResolver.GetEntity (uri, null, typeof (Stream));
					}
					catch {
						// may still be a local file (and maybe not xml)
						s = File.OpenRead (r.Uri);
					}
				}
				if (objectName != null) {
					XmlElement found = null;
					foreach (DataObject obj in m_signature.ObjectList) {
						if (obj.Id == objectName) {
							found = obj.GetXml ();
							found.SetAttribute ("xmlns", SignedXml.XmlDsigNamespaceUrl);
							doc.AppendChild (doc.ImportNode (found, true));
							// FIXME: there should be theoretical justification of copying namespace declaration nodes this way.
							foreach (XmlNode n in found.ChildNodes)
								// Do not copy default namespace as it must be xmldsig namespace for "Object" element.
								if (n.NodeType == XmlNodeType.Element)
									FixupNamespaceNodes (n as XmlElement, doc.DocumentElement, true);
							break;
						}
					}
					if (found == null && envdoc != null) {
						found = GetIdElement (envdoc, objectName);
						if (found != null) {
							doc.AppendChild (doc.ImportNode (found, true));
							FixupNamespaceNodes (found, doc.DocumentElement, false);
						}
					}
					if (found == null)
						throw new CryptographicException (String.Format ("Malformed reference object: {0}", objectName));
				}
			}

			if (r.TransformChain.Count > 0) {		
				foreach (Transform t in r.TransformChain) {
					if (s == null) {
						s = ApplyTransform (t, doc);
					}
					else {
						t.LoadInput (s);
						object o = t.GetOutput ();
						if (o is Stream)
							s = (Stream) o;
						else
							s = CanonicalizeOutput (o);
					}
				}
			}
			else if (s == null) {
				// we must not C14N references from outside the document
				// e.g. non-xml documents
				if (r.Uri [0] != '#') {
					s = new MemoryStream ();
					doc.Save (s);
				}
				else {
					// apply default C14N transformation
					s = ApplyTransform (new XmlDsigC14NTransform (), doc);
				}
			}
			HashAlgorithm digest = GetHash (r.DigestMethod, check_hmac);
			return (digest == null) ? null : digest.ComputeHash (s);
		}
Exemplo n.º 39
0
        /// <summary>
        /// Firmar y Encriptar el Documento XML usando un Certificado x509.
        /// </summary>
        /// <param name="xmldoc">el documento XML a firmar y encriptar.</param>
        /// <param name="certificado">el certificado para poder firmar el XML</param>
        /// <param name="certificadopublico">el certificado publico para poder encriptar</param>
        /// <returns></returns>
        private static XmlDocument FirmaryEncriptarSoapRequest(XmlDocument xmldoc, X509Certificate2 certificadoPrivado, X509Certificate2 certificadopublico)
        {
            #region Firmar
            //añadir las referencias de espacios de nombres para asegurarnos de que podamos trabajar contra
            //cualquier documento elemento XML sin importar el nombramiento de los Tags siempre y cuando sepamos sus Namespaces.
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmldoc.NameTable);
            namespaceManager.AddNamespace("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            namespaceManager.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            namespaceManager.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");

            //Seleccionar el Header para agregarle elementos.
            XmlElement headerNode = xmldoc.DocumentElement.SelectSingleNode("//soapenv:Header", namespaceManager) as XmlElement;
            //Creamos el nodo de seguridad <Security>
            XmlElement securityNode = xmldoc.CreateElement("wsse", "Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            securityNode.SetAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            securityNode.SetAttribute("mustUnderstand", "http://schemas.xmlsoap.org/soap/envelope/", "1");
            XmlAttribute mustUnderstandSecurityAttribute = securityNode.GetAttributeNode("mustUnderstand");
            mustUnderstandSecurityAttribute.Prefix = "soapenv";



            #region Preparar elementos a ser firmados


            //Ahora vamos a crear otro BinarySecurityToken

            //Ahora creamos un BinarySecurityToken que será el certificado x509 de la clave privada
            //Con este BinarySecurityToken se espera que el receptor pueda verificar el Digest de la firma que se
            //genera con este BinarySecurityToken.
            //este BinarySecurityToken es firmado también.

            XmlElement binarySecurityTokenNode2 = xmldoc.CreateElement("wsse", "BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            //El atributo EncodingType dice cómo el Token está codificado, en este caso, Base64Binary.
            binarySecurityTokenNode2.SetAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
            //El atributo ValueType indica qué es el BinarySecurityToken, en este caso un Certificado X509v3.
            binarySecurityTokenNode2.SetAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");

            binarySecurityTokenNode2.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", XmlElementsIds.PrivateKeyBinarySecurityTokenUri);
            XmlAttribute attribute2 = binarySecurityTokenNode2.GetAttributeNode("Id");
            attribute2.Prefix = "wsu";
            binarySecurityTokenNode2.InnerText = Convert.ToBase64String(certificadoPrivado.GetRawCertData());

            //Creamos una estampa de tiempo, la cuál será firmada también:

            Timestamp timestamp = new Timestamp();
            timestamp.TtlInSeconds = 5000;

            //El body también será firmado, pero todavía no tiene los atributos requeridos para que pueda ser firmado
            //Aquí se los agrego.

            //Ahora vamos a ponerle un Id.
            XmlElement body = xmldoc.DocumentElement.SelectSingleNode("//soapenv:Body", namespaceManager) as XmlElement;
            body.SetAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            body.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", XmlElementsIds.BodyId);
            var bodyId = body.GetAttributeNode("Id");
            bodyId.Prefix = "wsu";

            #endregion

            #region Agregar elementos a ser firmados al nodo Security



            securityNode.AppendChild(timestamp.GetXml(xmldoc));
            securityNode.AppendChild(binarySecurityTokenNode2);
            //agregar
            headerNode.AppendChild(securityNode);
            //el body ya existe, y no pertenece al nodo security.

            #endregion

            //Al momento de computar la firma, la clase SignedXml buscará las referencias previamente puestas, (las busca por los Id de cada uno
            //de los elementos a ser firmados.
            //y firmará los elementos que las referencias han referenciado
            //valga la redundancia.

            #region Crear firma XML


            //Ahora vamos a agregar un elemento Signature, que representa la firma digital.

            SignedXml signedXml = new SignedXmlWithId(xmldoc);

            signedXml.Signature.Id = "SIG-3";
            //la canonicalización indica como se deben interpretar los espacios en blanco y similares
            //porque el valor de firma puede cambiar inclusive cuando hayan espacios u otros caracteres-
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            //cual fue el algoritmo usado para firmar.
            signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;

            //Cada una de las referencias apunta a un Id, que deberán tener los elementos
            //a ser firmados.


            System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference
            {
                Uri = "#" + XmlElementsIds.PrivateKeyBinarySecurityTokenUri
            };
            reference.AddTransform(new XmlDsigExcC14NTransform(""));
            reference.DigestMethod = SignedXml.XmlDsigSHA1Url;

            System.Security.Cryptography.Xml.Reference reference2 = new System.Security.Cryptography.Xml.Reference
            {
                Uri = "#" + timestamp.Id
            };
            reference2.AddTransform(new XmlDsigExcC14NTransform("wsse lib soapenv"));
            reference2.DigestMethod = SignedXml.XmlDsigSHA1Url;

            System.Security.Cryptography.Xml.Reference reference3 = new System.Security.Cryptography.Xml.Reference
            {
                Uri = "#" + XmlElementsIds.BodyId
            };
            reference3.AddTransform(new XmlDsigExcC14NTransform("lib"));
            reference3.DigestMethod = SignedXml.XmlDsigSHA1Url;


            signedXml.SignedInfo.AddReference(reference);
            signedXml.SignedInfo.AddReference(reference2);
            signedXml.SignedInfo.AddReference(reference3);
            signedXml.SigningKey = certificadoPrivado.PrivateKey; //la clave privada para firmar.

            //La Keyinfo representa un identificador de un Token de seguridad.
            //en el caso de las firmas, identifica cómo encontrar el token que se usó para firmar.
            KeyInfo keyInfoInsideSignature = new KeyInfo();
            keyInfoInsideSignature.Id = "KI-D313N3M1G0";

            //en este caso Una referencia a un token de seguridad.
            SecurityTokenReference securityTokenReferenceInsideSignature = new SecurityTokenReference();
            securityTokenReferenceInsideSignature.Id        = "STR-SecurityTokenReference";
            securityTokenReferenceInsideSignature.ValueType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
            securityTokenReferenceInsideSignature.Reference = XmlElementsIds.PrivateKeyBinarySecurityTokenUri; //El BinarySecurityToken que contiene el Certificado x509v3 usado para la firma (usando su clave privada)
            KeyInfoClause keyInfoClauseInsideSignature = new KeyInfoNode(securityTokenReferenceInsideSignature.GetXml());
            keyInfoInsideSignature.AddClause(keyInfoClauseInsideSignature);

            signedXml.KeyInfo = keyInfoInsideSignature;


            signedXml.ComputeSignature();

            //revisar que la firma sea válida.(para propósitos de desarrollo)
            bool    firstcheck    = signedXml.CheckSignature(certificadoPrivado, true);
            XmlNode signatureNode = signedXml.GetXml(); //Finalmente ya obtenemos un elemento <signature> totalmente formado y listo para ser anexado al nodo <security>
            #endregion


            securityNode.AppendChild(signatureNode);



            #endregion

            #region Encriptar

            //Ahora vamos a obtener el certificado público, y usar su clave para encriptar el contenido del body

            Encriptar(ref xmldoc, "lib:quotationCarGenericRq", certificadopublico, ref securityNode);

            #endregion

            //Devolver un XML Firmado y Encriptado.
            #region testing, se puede dejar comentado:
            //HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://wsqa.libertycolombia.com.co:8443/soa-infra/services/GenericAuto/GenericAutoQuotation/GenericAutoQuotationMediator_ep");
            //req.Headers.Add("SOAPAction", "urn:quotationCarGeneric");
            //req.Method = "POST";
            //req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";
            //req.ContentType = "text/xml;charset=\"utf-8\"";
            //req.Host = "wsqa.libertycolombia.com.co:8443";

            ////XmlDocument xmldoctest = new XmlDocument();
            ////xmldoctest.Load(@"C:\Users\CarlosAlbertoFiguere\Desktop\test.xml");

            //using (Stream stream = req.GetRequestStream())
            //{
            //    using (StreamWriter streamWriter = new StreamWriter(stream))
            //    {
            //        streamWriter.Write(xmldoc.OuterXml);

            //    }

            //}
            //try
            //{
            //    WebResponse lol = req.GetResponse();
            //    string response = (new StreamReader(lol.GetResponseStream())).ReadToEnd();

            //}
            //catch (WebException wex)
            //{
            //    string response = (new StreamReader(wex.Response.GetResponseStream())).ReadToEnd();
            //}
            #endregion

            return(xmldoc);
        }
Exemplo n.º 40
0
        public static string SignXmlFile(string xml, RSA Key)
        {
            // Create a new XML document.
            var doc = new XmlDocument();

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

            using (var textReader = new StringReader(xml))
            {
                doc.Load(new XmlTextReader(textReader));
            }

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

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

            // Specify a canonicalization method.
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Set the InclusiveNamespacesPrefixList property.        
            var canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;
            var ref1 = new Reference("#Body52be6364-045f-1550-625d-b20b0390691e");
            var ref2 = new Reference("#Timestamp5257ab43-882c-4937-3835-6763e9a2d700");

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

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

            string keyInfoStr = "<KeyInfo><wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:Reference URI=\"#holderOfKeyCertificate\" ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\"/></wsse:SecurityTokenReference></KeyInfo>";
            var xd = new XmlDocument();
            xd.LoadXml(keyInfoStr);

            var ki = new KeyInfo();
            ki.LoadXml(xd.DocumentElement);
            signedXml.KeyInfo = ki;

            // Compute the signature.
            //signedXml.ComputeSignature(KeyedHashAlgorithm.Create("HMACSHA256"));
            signedXml.ComputeSignature();

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

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            {
                using (var writer = new XmlTextWriter(sw))
                {
                    xmlDigitalSignature.WriteTo(writer);
                }
            }
            return sb.ToString();
        }
Exemplo n.º 41
0
        private bool WriteLicenseToFile(string appDir, bool spfold, int version)
        {
            var str1 = string.Format("{0}-{1}-{2}-{3}-{4}", "U3", "AAAA", "AAAA", "AAAA", "AAAA");

            var byteList1 = new List <byte>();


            byteList1.AddRange(Encoding.ASCII.GetBytes(string.Format("{0}-{1}", str1, "NUUN")));
            if (version != 20172)
            {
                List <string> stringList = new List <string>()
                {
                    "<root>",
                    "  <TimeStamp2 Value=\"cn/lkLOZ3vFvbQ==\"/>",
                    "  <TimeStamp Value=\"jWj8PXAeZMPzUw==\"/>",
                    "  <License id=\"Terms\">",
                    "    <ClientProvidedVersion Value=\"\"/>",
                    string.Format("    <DeveloperData Value=\"{0}\"/>", (object)Convert.ToBase64String(byteList1.ToArray())),
                    "    <Features>"
                };

                foreach (var num in LicHeader.ReadAll())
                {
                    stringList.Add(string.Format("      <Feature Value=\"{0}\"/>", (object)num));
                }
                stringList.Add("    </Features>");
                if (version < 500)
                {
                    stringList.Add("    <LicenseVersion Value=\"4.x\"/>");
                }
                if (version >= 500 && version < 2017)
                {
                    stringList.Add("    <LicenseVersion Value=\"5.x\"/>");
                }
                if (version == 2017)
                {
                    stringList.Add("    <LicenseVersion Value=\"2017.x\"/>");
                }
                if (version == 20171)
                {
                    stringList.Add("    <LicenseVersion Value=\"6.x\"/>");
                }
                stringList.Add("    <MachineBindings>");
                stringList.Add("    </MachineBindings>");
                stringList.Add("    <MachineID Value=\"\"/>");
                stringList.Add("    <SerialHash Value=\"\"/>");
                stringList.Add(string.Format("    <SerialMasked Value=\"{0}-XXXX\"/>", (object)str1));
                DateTime now = DateTime.Now;
                stringList.Add(string.Format("    <StartDate Value=\"{0}T00:00:00\"/>", (object)now.AddDays(-1.0).ToString("yyyy-MM-dd")));
                stringList.Add("    <StopDate Value=\"\"/>");
                stringList.Add(string.Format("    <UpdateDate Value=\"{0}T00:00:00\"/>", (object)now.AddYears(10).ToString("yyyy-MM-dd")));
                stringList.Add("  </License>");
                stringList.Add("");
                stringList.Add("<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">");
                stringList.Add("<SignedInfo>");
                stringList.Add("<CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments\"/>");
                stringList.Add("<SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>");
                stringList.Add("<Reference URI=\"#Terms\">");
                stringList.Add("<Transforms>");
                stringList.Add("<Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>");
                stringList.Add("</Transforms>");
                stringList.Add("<DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>");
                stringList.Add("<DigestValue>oeMc1KScgy617DHMPTxbYhqNjIM=</DigestValue>");
                stringList.Add("</Reference>");
                stringList.Add("</SignedInfo>");
                stringList.Add("<SignatureValue>WuzMPTi0Ko1vffk9gf9ds/iU0b0K8UHaLpi4kWgm6q1am5MPTYYnzH1InaSWuzYo");
                stringList.Add("EpJThKspOZdO0JISeEolNdJVf3JpsY55OsD8UaruvhwZn4r9pLeNSC7SzQ1rvAWP");
                stringList.Add("h77XaHizhVVs15w6NYevP27LTxbZaem5L8Zs+34VKXQFeG4g0dEI/Jhl70TqE0CS");
                stringList.Add("YNF+D0zqEtyMNHsh0Rq/vPLSzPXUN12jfPLZ3dO9B+9/mG7Ljd6emZjjLZUVuSKQ");
                stringList.Add("uKxN5jlHZsm2kRMudijICV6YOWMPT+oZePlCg+BJQg5/xcN5aYVBDZhNeuNwQL1H");
                stringList.Add("MPT/GJPxVuETgd9k8c4uDg==</SignatureValue>");
                stringList.Add("</Signature>");
                stringList.Add("</root>");

                string str2 = "";
                if (version < 500)
                {
                    str2 = "Unity_v4.x.ulf";
                }
                if (version >= 500 && version < 2017)
                {
                    str2 = "Unity_v5.x.ulf";
                }
                if (version == 2017)
                {
                    str2 = "Unity_v2017.x.ulf";
                }
                if (version == 20171)
                {
                    str2 = "Unity_lic.ulf";
                }

                var path = string.Empty;
                if (spfold)
                {
                    path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Unity";
                    if (!Directory.Exists(path))
                    {
                        try
                        {
                            Directory.CreateDirectory(path);
                        }
                        catch (Exception ex)
                        {
                            spfold = false;
                            var num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                        }
                    }
                }
                if (spfold)
                {
                    if (File.Exists(path + "/" + str2))
                    {
                        spfold = TestAtr(path + "/" + str2);
                        if (spfold && MessageBox.Show(string.Format("Replace the \"{0}\\{1}\"?", path, str2), string.Empty,
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.OK)
                        {
                            stringList.Clear();
                            return(true);
                        }
                    }
                    if (spfold)
                    {
                        try
                        {
                            if (version < 500)
                            {
                                str2 = "Unity_v4.x.ulf";
                            }
                            if (version >= 500 && version < 2017)
                            {
                                str2 = "Unity_v5.x.ulf";
                            }
                            if (version == 2017)
                            {
                                str2 = "Unity_v2017.x.ulf";
                            }
                            if (version == 20171)
                            {
                                str2 = "Unity_lic.ulf";
                            }
                            if (str2 == "Unity_lic.ulf")
                            {
                                using (FileStream fileStream = new FileStream(path + "/" + str2, FileMode.Append))
                                {
                                    foreach (object obj in stringList)
                                    {
                                        byte[] bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r", obj));
                                        fileStream.Write(bytes, 0, bytes.Length);
                                    }
                                    fileStream.Flush();
                                    fileStream.Close();
                                }
                            }
                            else
                            {
                                File.WriteAllLines(path + "/" + str2, (IEnumerable <string>)stringList);
                            }
                        }
                        catch (Exception ex)
                        {
                            spfold = false;
                            int num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                        }
                    }
                }
                if (!spfold)
                {
                    if (File.Exists(appDir + "/" + str2))
                    {
                        if (TestAtr(appDir + "/" + str2))
                        {
                            if (MessageBox.Show(string.Format("Replace the \"{0}\\{1}\"?", appDir, str2), string.Empty,
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
                                System.Windows.Forms.DialogResult.OK)
                            {
                                stringList.Clear();
                                return(true);
                            }
                        }
                        else
                        {
                            stringList.Clear();
                            return(false);
                        }
                    }
                    try
                    {
                        if (version < 500)
                        {
                            str2 = "Unity_v4.x.ulf";
                        }
                        if (version >= 500 && version < 2017)
                        {
                            str2 = "Unity_v5.x.ulf";
                        }
                        if (version == 2017)
                        {
                            str2 = "Unity_v2017.x.ulf";
                        }
                        if (version == 20171)
                        {
                            str2 = "Unity_lic.ulf";
                        }
                        if (str2 == "Unity_lic.ulf")
                        {
                            using (FileStream fileStream = new FileStream(path + "/" + str2, FileMode.Append))
                            {
                                foreach (object obj in stringList)
                                {
                                    byte[] bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r", obj));
                                    fileStream.Write(bytes, 0, bytes.Length);
                                }
                                fileStream.Flush();
                                fileStream.Close();
                            }
                        }
                        else
                        {
                            File.WriteAllLines(path + "/" + str2, (IEnumerable <string>)stringList);
                        }
                    }
                    catch (Exception ex)
                    {
                        stringList.Clear();
                        int num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                        return(false);
                    }
                }
                stringList.Clear();
                return(true);
            }
            string s = string.Format("{0}-{1}-{2}-{3}-{4}-{5}", "U3", "AAAA", "AAAA", "AAAA", "AAAA", "AAAA");

            int[] numArray = LicHeader.ReadAll();
            if (s.Length != 27)
            {
                int num = (int)MessageBox.Show("Invalid Key must be \"27\" chars.", string.Empty, MessageBoxButtons.OK);
                return(false);
            }
            string path2        = "Unity_lic.ulf";
            string str3         = s.Remove(s.Length - 4, 4) + "XXXX";
            string base64String = Convert.ToBase64String(((IEnumerable <byte>)((IEnumerable <byte>) new byte[4]
            {
                (byte)1,
                (byte)0,
                (byte)0,
                (byte)0
            }).Concat <byte>((IEnumerable <byte>)Encoding.ASCII.GetBytes(s)).ToArray <byte>()).ToArray <byte>());
            string   str4     = "6.x";
            string   str5     = "false";
            string   str6     = "";
            DateTime dateTime = DateTime.UtcNow;

            dateTime = dateTime.AddDays(-1.0);
            string str7 = dateTime.ToString("s", (IFormatProvider)CultureInfo.InvariantCulture);
            Dictionary <string, string> dictionary = new Dictionary <string, string>();
            string str8  = "";
            string str9  = "";
            string str10 = "";
            string str11 = "";

            dateTime = DateTime.UtcNow;
            dateTime = dateTime.AddYears(10);
            string            str12        = dateTime.ToString("s", (IFormatProvider)CultureInfo.InvariantCulture);
            MemoryStream      memoryStream = new MemoryStream();
            XmlWriterSettings settings     = new XmlWriterSettings()
            {
                Indent             = true,
                IndentChars        = "  ",
                NewLineChars       = "\n",
                OmitXmlDeclaration = true,
                Encoding           = Encoding.ASCII
            };

            using (XmlWriter xmlWriter = XmlWriter.Create((Stream)memoryStream, settings))
            {
                xmlWriter.WriteStartElement("root");
                xmlWriter.WriteStartElement("License");
                xmlWriter.WriteAttributeString("id", "Terms");
                xmlWriter.WriteStartElement("AlwaysOnline");
                xmlWriter.WriteAttributeString("Value", str5);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("ClientProvidedVersion");
                xmlWriter.WriteAttributeString("Value", str6);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("DeveloperData");
                xmlWriter.WriteAttributeString("Value", base64String);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("Features");
                foreach (int num in numArray)
                {
                    xmlWriter.WriteStartElement("Feature");
                    xmlWriter.WriteAttributeString("Value", num.ToString());
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteFullEndElement();
                xmlWriter.WriteStartElement("InitialActivationDate");
                xmlWriter.WriteAttributeString("Value", str7);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("LicenseVersion");
                xmlWriter.WriteAttributeString("Value", str4);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("MachineBindings");
                foreach (KeyValuePair <string, string> keyValuePair in dictionary)
                {
                    xmlWriter.WriteStartElement("Binding");
                    xmlWriter.WriteAttributeString("Key", keyValuePair.Key);
                    xmlWriter.WriteAttributeString("Value", keyValuePair.Value);
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteFullEndElement();
                xmlWriter.WriteStartElement("MachineID");
                xmlWriter.WriteAttributeString("Value", str8);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("SerialHash");
                xmlWriter.WriteAttributeString("Value", str9);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("SerialMasked");
                xmlWriter.WriteAttributeString("Value", str3);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("StartDate");
                xmlWriter.WriteAttributeString("Value", str10);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("StopDate");
                xmlWriter.WriteAttributeString("Value", str11);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("UpdateDate");
                xmlWriter.WriteAttributeString("Value", str12);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
            }
            memoryStream.Position = 0L;
            XmlDocument document = new XmlDocument()
            {
                PreserveWhitespace = true
            };

            document.Load((Stream)memoryStream);
            SignedXml signedXml = new SignedXml(document)
            {
                SigningKey = (AsymmetricAlgorithm) new RSACryptoServiceProvider()
            };
            Reference reference = new Reference()
            {
                Uri = "#Terms"
            };

            reference.AddTransform((System.Security.Cryptography.Xml.Transform) new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            StringBuilder output = new StringBuilder();

            using (XmlWriter w = XmlWriter.Create(output, settings))
            {
                XmlDocument xmlDocument1 = new XmlDocument();
                string      innerXml     = document.InnerXml;
                xmlDocument1.InnerXml = innerXml;
                XmlDocument xmlDocument2    = xmlDocument1;
                XmlElement  documentElement = xmlDocument2.DocumentElement;
                if (documentElement != null)
                {
                    XmlNode newChild = xmlDocument2.ImportNode((XmlNode)signedXml.GetXml(), true);
                    documentElement.AppendChild(newChild);
                }
                xmlDocument2.Save(w);
                w.Flush();
            }
            string contents = output.Replace(" />", "/>").ToString();
            string str13    = spfold ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Unity") : appDir;
            string path1    = Path.Combine(str13, path2);

            try
            {
                Directory.CreateDirectory(str13);
                if (File.Exists(path1) && this.TestAtr(path1) && MessageBox.Show(string.Format("Replace the \"{0}\"?", (object)path1), string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.OK)
                {
                    return(true);
                }
                File.WriteAllText(path1, contents);
            }
            catch (Exception ex)
            {
                int num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                return(false);
            }
            return(true);
        }