Ejemplo n.º 1
0
        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, X509Certificate2 Cert)
        {
            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");
            }
            EncryptedXml  eXml      = new EncryptedXml();
            EncryptedData edElement = eXml.Encrypt(elementToEncrypt, Cert);

            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }
Ejemplo n.º 2
0
        public static XmlElement Encrypt(SmtpAddress externalId, SymmetricSecurityKey symmetricSecurityKey)
        {
            XmlDocument xmlDocument = new SafeXmlDocument();
            XmlElement  xmlElement  = xmlDocument.CreateElement("SharingKey");

            xmlElement.InnerText = externalId.ToString();
            EncryptedXml encryptedXml = new EncryptedXml();

            encryptedXml.AddKeyNameMapping("key", symmetricSecurityKey.GetSymmetricAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc"));
            EncryptedData encryptedData = encryptedXml.Encrypt(xmlElement, "key");

            return(encryptedData.GetXml());
        }
Ejemplo n.º 3
0
    public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, SymmetricAlgorithm Alg, string KeyName)
    {
        // Check the arguments.
        if (Doc == null)
        {
            throw new ArgumentNullException("Doc");
        }
        if (ElementToEncrypt == null)
        {
            throw new ArgumentNullException("ElementToEncrypt");
        }
        if (Alg == null)
        {
            throw new ArgumentNullException("Alg");
        }

        ////////////////////////////////////////////////
        // Find the specified element in the XmlDocument
        // object and create a new XmlElemnt object.
        ////////////////////////////////////////////////

        XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

        // Throw an XmlException if the element was not found.
        if (elementToEncrypt == null)
        {
            throw new XmlException("The specified element was not found");
        }

        //////////////////////////////////////////////////
        // Create a new instance of the EncryptedXml class
        // and use it to encrypt the XmlElement with the
        // symmetric key.
        //////////////////////////////////////////////////

        EncryptedXml eXml = new EncryptedXml();

        // Add the key mapping.
        eXml.AddKeyNameMapping(KeyName, Alg);

        // Encrypt the element.
        EncryptedData edElement = eXml.Encrypt(elementToEncrypt, KeyName);


        ////////////////////////////////////////////////////
        // Replace the element from the original XmlDocument
        // object with the EncryptedData element.
        ////////////////////////////////////////////////////

        EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
    }
Ejemplo n.º 4
0
        public override XmlNode Encrypt(XmlNode node)
        {
            XmlDocument doc = new ConfigurationXmlDocument();

            doc.Load(new StringReader(node.OuterXml));

            EncryptedXml ex = new EncryptedXml(doc);

            ex.AddKeyNameMapping("Rsa Key", GetProvider());

            EncryptedData d = ex.Encrypt(doc.DocumentElement, "Rsa Key");

            return(d.GetXml());
        }
    public override XmlNode Encrypt(XmlNode node)
    {
        // Load config section to encrypt into xmlDocument instance
        XmlDocument doc = new XmlDocument {
            PreserveWhitespace = true
        };

        doc.LoadXml(node.OuterXml);

        // Encrypt it
        EncryptedXml  eXml  = new EncryptedXml();
        EncryptedData eData = eXml.Encrypt(doc.DocumentElement, this.cert);

        return(eData.GetXml());
    }
    public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, X509Certificate2 Cert)
    {
        // Check the arguments.
        if (Doc == null)
        {
            throw new ArgumentNullException("Doc");
        }
        if (ElementToEncrypt == null)
        {
            throw new ArgumentNullException("ElementToEncrypt");
        }
        if (Cert == null)
        {
            throw new ArgumentNullException("Cert");
        }

        ////////////////////////////////////////////////
        // Find the specified element in the XmlDocument
        // object and create a new XmlElemnt object.
        ////////////////////////////////////////////////

        XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

        // Throw an XmlException if the element was not found.
        if (elementToEncrypt == null)
        {
            throw new XmlException("The specified element was not found");
        }

        //////////////////////////////////////////////////
        // Create a new instance of the EncryptedXml class
        // and use it to encrypt the XmlElement with the
        // X.509 Certificate.
        //////////////////////////////////////////////////

        EncryptedXml eXml = new EncryptedXml();

        // Encrypt the element.
        EncryptedData edElement = eXml.Encrypt(elementToEncrypt, Cert);


        ////////////////////////////////////////////////////
        // Replace the element from the original XmlDocument
        // object with the EncryptedData element.
        ////////////////////////////////////////////////////

        EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
    }
Ejemplo n.º 7
0
        EncryptedData IInternalCertificateXmlEncryptor.PerformEncryption(EncryptedXml encryptedXml, XmlElement elementToEncrypt)
        {
            var cert = _certFactory();                                                                            // original CryptoUtil.Fail call removed

            _logger.LogDebug("Encrypting to X.509 certificate with thumbprint '{Thumbprint}'.", cert.Thumbprint); // original ILogger extensions calls replaced

            try
            {
                return(encryptedXml.Encrypt(elementToEncrypt, cert));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An error occurred while encrypting to X.509 certificate with thumbprint '{Thumbprint}'.", cert.Thumbprint); // original ILogger extensions calls replaced
                throw;
            }
        }
        EncryptedData IInternalCertificateXmlEncryptor.PerformEncryption(EncryptedXml encryptedXml, XmlElement elementToEncrypt)
        {
            var cert = _certFactory()
                       ?? CryptoUtil.Fail <X509Certificate2>("Cert factory returned null.");

            _logger?.EncryptingToX509CertificateWithThumbprint(cert.Thumbprint);

            try
            {
                return(encryptedXml.Encrypt(elementToEncrypt, cert));
            }
            catch (Exception ex)
            {
                _logger?.AnErrorOccurredWhileEncryptingToX509CertificateWithThumbprint(cert.Thumbprint, ex);
                throw;
            }
        }
Ejemplo n.º 9
0
        private static void encryptDocument(X509Certificate2 cert, XmlDocument doc)
        {
            string encData = "<root xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"  xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                             "<xenc:EncryptedKey xmlns:xenc=\"http://www.w3.org/2001/04/xmlenc#\" Id=\"Cert\"><xenc:EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#rsa-1_5\">" +
                             "</xenc:EncryptionMethod><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">" +
                             "<wsse:SecurityTokenReference><wsse:KeyIdentifier EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\" ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\">" +
                             "</wsse:KeyIdentifier></wsse:SecurityTokenReference></ds:KeyInfo><xenc:CipherData><xenc:CipherValue></xenc:CipherValue></xenc:CipherData>" +
                             "<xenc:ReferenceList><xenc:DataReference URI=\"#Body\"></xenc:DataReference></xenc:ReferenceList></xenc:EncryptedKey></root>";

            XmlDocument encryptedDataTags = new XmlDocument();

            encryptedDataTags.LoadXml(encData);
            doc.DocumentElement.FirstChild.FirstChild.PrependChild(doc.ImportNode(encryptedDataTags.FirstChild.FirstChild, true));

            XmlElement   elementToEncrypt = doc.GetElementsByTagName(REQUEST_MESSAGE)[0] as XmlElement;
            EncryptedXml eXml             = new EncryptedXml();

            // Encrypt the element.
            EncryptedData edElement = eXml.Encrypt(elementToEncrypt, cert);

            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);

            // Extract cybs certificate and put it in keyidentifier tag
            XmlNodeList serverCert = doc.GetElementsByTagName("X509Certificate");

            doc.GetElementsByTagName("wsse:KeyIdentifier")[0].InnerText = serverCert[0].InnerText;

            // Extract ciphervalues
            XmlNodeList tempkey          = doc.GetElementsByTagName("CipherValue");
            string      encryptedPayload = tempkey[1].InnerText;

            // Put temporary encrypted key in ciphervalue tag inside keyinfo
            doc.GetElementsByTagName("xenc:CipherValue")[0].InnerText = tempkey[0].InnerText;

            string encryptedSoapBody = "<xenc:EncryptedData xmlns:xenc=\"http://www.w3.org/2001/04/xmlenc#\" Id=\"Body\" Type=\"http://www.w3.org/2001/04/xmlenc#Content\">" +
                                       "<xenc:EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\">" +
                                       "</xenc:EncryptionMethod><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">" +
                                       "<wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                                       "<wsse:Reference URI=\"#Cert\"></wsse:Reference></wsse:SecurityTokenReference></ds:KeyInfo><xenc:CipherData><xenc:CipherValue>" +
                                       "</xenc:CipherValue></xenc:CipherData></xenc:EncryptedData>";

            // Put encypted body inside ciphervalue tag
            doc.GetElementsByTagName("SOAP-ENV:Body")[0].InnerXml     = encryptedSoapBody;
            doc.GetElementsByTagName("xenc:CipherValue")[1].InnerText = encryptedPayload;
        }
Ejemplo n.º 10
0
        public static string SerializeAndSignSAMLResponse(ResponseType Response)
        {
            // Set serializer and writers for action
            XmlSerializer responseSerializer = new XmlSerializer(Response.GetType());
            StringWriter  stringWriter       = new StringWriter();
            XmlWriter     responseWriter     = XmlTextWriter.Create(stringWriter, new XmlWriterSettings()
            {
                OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8
            });

            responseSerializer.Serialize(responseWriter, Response);
            responseWriter.Close();
            XmlDocument xmlResponse = new XmlDocument();

            xmlResponse.LoadXml(stringWriter.ToString());
            XmlElement elementToEncrypt = xmlResponse.GetElementsByTagName("saml:Assertion")[0] as XmlElement;

            /////////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class //
            // and use it to encrypt the XmlElement with the   //
            // X.509 Certificate.                              //
            /////////////////////////////////////////////////////

            EncryptedXml eXml = new EncryptedXml();

            // Encrypt the element.
            X509Certificate2 certificate = new X509Certificate2(@"C:\Program Files\OpenSSL-Win64\bin\certificate.crt");//SAMLConfiguration.Current.CertificateManager.GetPartnerCertificate(partnerSP);
            //X509Certificate2 certificate2 = new X509Certificate2(@"C:\Program Files\OpenSSL-Win64\bin\certificate1.pfx", "VSIP@ssw0rd");
            //certificate.Import(@"C:\Program Files\OpenSSL-Win64\bin\certificate.crt");
            EncryptedData edElement = eXml.Encrypt(elementToEncrypt, certificate);

            XmlElement encryptedAssertion = xmlResponse.CreateElement("saml", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");

            EncryptedXml.ReplaceElement(encryptedAssertion, edElement, true);

            ///////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument //
            // object with the EncryptedData element.            //
            ///////////////////////////////////////////////////////
            xmlResponse.GetElementsByTagName("Response")[0].ReplaceChild(encryptedAssertion, elementToEncrypt);

            return(xmlResponse.OuterXml);
        }
Ejemplo n.º 11
0
        private void CheckEncryptionMethod(object algorithm, string uri)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<root />");
            EncryptedXml exml = new EncryptedXml();

            exml.AddKeyNameMapping("key", algorithm);

            EncryptedData edata       = exml.Encrypt(doc.DocumentElement, "key");
            IEnumerator   keyInfoEnum = edata.KeyInfo.GetEnumerator();

            keyInfoEnum.MoveNext();
            KeyInfoEncryptedKey kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;

            Assert.NotNull(edata);
            Assert.Equal(uri, kiEncKey.EncryptedKey.EncryptionMethod.KeyAlgorithm);
            Assert.NotNull(edata.CipherData.CipherValue);
        }
Ejemplo n.º 12
0
        public void DecryptData_CipherReference_InvalidUri()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            using (Aes aes = Aes.Create())
            {
                EncryptedXml exml = new EncryptedXml();
                exml.AddKeyNameMapping("aes", aes);
                EncryptedData ed = exml.Encrypt(doc.DocumentElement, "aes");
                ed.CipherData = new CipherData();
                ed.CipherData.CipherReference = new CipherReference("invaliduri");

                Assert.Throws <CryptographicException>(() => exml.DecryptData(ed, aes));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Encrypt the element within the xml document.
        /// </summary>
        /// <param name="document">The xml document containing the element to encrypt.</param>
        /// <param name="elementToEncrypt">The element to encrypt.</param>
        /// <param name="certificate">The certificate used to encrypt the element.</param>
        public void Encrypt(XmlDocument document, string elementToEncrypt, X509Certificate2 certificate)
        {
            // Check the arguments.
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (string.IsNullOrEmpty(elementToEncrypt))
            {
                throw new ArgumentNullException("elementToEncrypt");
            }

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


            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            XmlElement element = document.GetElementsByTagName(elementToEncrypt)[0] as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");
            }

            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // X.509 Certificate.
            EncryptedXml eXml = new EncryptedXml();

            // Encrypt the element.
            EncryptedData edElement = eXml.Encrypt(element, certificate);

            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            EncryptedXml.ReplaceElement(element, edElement, false);
        }
Ejemplo n.º 14
0
        // Зашифрование узла в адрес абонента, заданного сертификатом
        // получателя.
        static void Encrypt(XmlDocument Doc, string xpath,
                            X509Certificate2 Cert)
        {
            // Ищем заданный элемент для заширования.
            XmlElement elementToEncrypt = Doc.SelectSingleNode(xpath) as XmlElement;

            if (elementToEncrypt == null)
            {
                throw new XmlException("Узел не найден");
            }

            // Создаем объект EncryptedXml для
            // шифрования XmlElement
            EncryptedXml eXml = new EncryptedXml();

            // Шифруем элемент на сертификате.
            EncryptedData edElement = eXml.Encrypt(elementToEncrypt, Cert);

            // Заменяем исходный элемент XML документа зашифрованным.
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }
Ejemplo n.º 15
0
        public static XDocument EncodeXML(XmlDocument srcDoc)
        {
            if (srcDoc == null)
            {
                return(null);
            }
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(x302c4346ab49b3404);
            EncryptedXml encXml = new EncryptedXml(srcDoc);

            encXml.AddKeyNameMapping("asyncKey", rsa);
            var docElement = srcDoc.DocumentElement;

            if (docElement != null)
            {
                EncryptedData encryptedData = encXml.Encrypt(docElement, "asyncKey");
                EncryptedXml.ReplaceElement(docElement, encryptedData, false);
            }
            return(XDocument.Parse(srcDoc.OuterXml));
        }
        public static void DecryptWithCertificate_NotInStore()
        {
            const string SecretMessage = "Grilled cheese is tasty";

            XmlDocument document = new XmlDocument();
            document.LoadXml($"<data><secret>{SecretMessage}</secret></data>");
            XmlElement toEncrypt = (XmlElement)document.DocumentElement.FirstChild;

            var cert = TestHelpers.GetSampleX509Certificate();
            EncryptedXml encryptor = new EncryptedXml(document);
            EncryptedData encryptedElement = encryptor.Encrypt(toEncrypt, cert.Item1);
            EncryptedXml.ReplaceElement(toEncrypt, encryptedElement, false);
                
            XmlDocument document2 = new XmlDocument();
            document2.LoadXml(document.OuterXml);

            EncryptedXml decryptor = new EncryptedXml(document2);

            Assert.Throws<System.Security.Cryptography.CryptographicException>(() => decryptor.DecryptDocument());
            Assert.DoesNotContain(SecretMessage, document2.OuterXml);
        }
Ejemplo n.º 17
0
        public void ReplaceData2NonDocumentElementTest()
        {
            XmlDocument doc = new XmlDocument();

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

            using (Rijndael aes = new RijndaelManaged())
            {
                aes.GenerateKey();
                aes.GenerateIV();

                // Encrypt the XML document
                EncryptedXml encryptedXml = new EncryptedXml(doc);
                encryptedXml.AddKeyNameMapping("key", aes);

                XmlElement    secretElement = doc.GetElementsByTagName("child")[0] as XmlElement;
                EncryptedData encrypted     = encryptedXml.Encrypt(secretElement, "key");
                EncryptedXml.ReplaceElement(secretElement, encrypted, false);

                // Decrypt it back
                XmlElement encryptedElement = doc.GetElementsByTagName("EncryptedData", EncryptedXml.XmlEncNamespaceUrl)[0] as XmlElement;

                EncryptedData encryptedData = new EncryptedData();
                encryptedData.LoadXml(encryptedElement);

                EncryptedXml decryptXml = new EncryptedXml(doc);
                decryptXml.AddKeyNameMapping("key", aes);

                byte[] decryptedData = decryptXml.DecryptData(encryptedData,
                                                              decryptXml.GetDecryptionKey(encryptedData, null));
                decryptXml.ReplaceData2(encryptedElement, decryptedData);
            }

            // Now that we've encrypted and decrypted the data, ensure that we have both the XML
            // declaration, and the root node in place.
            Assert.IsTrue(doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration);
            Assert.AreEqual("root", doc.FirstChild.NextSibling.Name);
            Assert.AreEqual(InputXml, doc.OuterXml);
        }
        public void Encrypt_X509()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            var           certificate = TestHelpers.GetSampleX509Certificate();
            EncryptedXml  exml        = new EncryptedXml();
            EncryptedData ed          = exml.Encrypt(doc.DocumentElement, certificate.Item1);

            Assert.NotNull(ed);

            doc.LoadXml(ed.GetXml().OuterXml);
            XmlNamespaceManager nm = new XmlNamespaceManager(doc.NameTable);

            nm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);

            Assert.NotNull(doc.SelectSingleNode("//enc:EncryptedKey", nm));
            Assert.DoesNotContain("sample", doc.OuterXml);
        }
Ejemplo n.º 19
0
        public void Encrypt_DecryptDocument_AES()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            using (Aes aes = Aes.Create())
            {
                EncryptedXml exml = new EncryptedXml();
                exml.AddKeyNameMapping("aes", aes);
                EncryptedData ed = exml.Encrypt(doc.DocumentElement, "aes");

                doc.LoadXml(ed.GetXml().OuterXml);
                EncryptedXml exmlDecryptor = new EncryptedXml(doc);
                exmlDecryptor.AddKeyNameMapping("aes", aes);
                exmlDecryptor.DecryptDocument();

                Assert.Equal(xml, doc.OuterXml);
            }
        }
Ejemplo n.º 20
0
        EncryptedData IInternalCertificateXmlEncryptor.PerformEncryption(EncryptedXml encryptedXml, XmlElement elementToEncrypt)
        {
            var cert = _certFactory()
                       ?? CryptoUtil.Fail <X509Certificate2>("Cert factory returned null.");

            if (_logger.IsVerboseLevelEnabled())
            {
                _logger.LogVerboseF($"Encrypting to X.509 certificate with thumbprint '{cert.Thumbprint}'.");
            }

            try
            {
                return(encryptedXml.Encrypt(elementToEncrypt, cert));
            }
            catch (Exception ex)
            {
                if (_logger.IsErrorLevelEnabled())
                {
                    _logger.LogErrorF(ex, $"An error occurred while encrypting to X.509 certificate with thumbprint '{cert.Thumbprint}'.");
                }
                throw;
            }
        }
        private XmlDocument GetTransformedOutput(XmlDocument doc, string nodeToEncrypt)
        {
            using (var aesAlgo = Aes.Create())
            {
                var encryptedXml = new EncryptedXml();
                encryptedXml.AddKeyNameMapping("aes", aesAlgo);
                XmlElement    elementToEncrypt = (XmlElement)doc.DocumentElement.SelectSingleNode(nodeToEncrypt);
                EncryptedData encryptedData    = encryptedXml.Encrypt(elementToEncrypt, "aes");
                EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false);

                XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable);
                xmlNamespaceManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
                XmlElement encryptedNode = (XmlElement)doc.DocumentElement.SelectSingleNode("//enc:EncryptedData", xmlNamespaceManager);
                encryptedNode.SetAttribute("ID", "#_0");

                transform.LoadInput(doc);
                transform.EncryptedXml = encryptedXml;
                XmlDocument transformedDocument = (XmlDocument)transform.GetOutput();

                transform.EncryptedXml = null;

                return(transformedDocument);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Шифрует XML файл по пути
        /// </summary>
        /// <param name="filename">Путь файла</param>
        /// <returns>Путь зашифрованного файла</returns>
        public string encryptXml(string filename)
        {
            if (externalFileSign) // Если выставлен флаг подписи внешними средствами - грузим его.
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = Path.GetTempPath();
                ofd.Filter           = "*.xml|*.xml";
                string f = null;
                while (f == null)
                {
                    ofd.ShowDialog();
                    f = ofd.FileName;
                }
                filename = f;
            }
            if (!File.Exists(filename))
            {
                throw new Exception("Шаг 3. Файл не найден!\r\nПуть:" + filename);
            }

            string filename3 = filename + ".encrypted.xml";

            // Открываем файл для шифрования
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(filename);

            // Шифруем по методу создания ключа обмена
            EncryptedXml  eXml      = new EncryptedXml();
            EncryptedData edElement = eXml.Encrypt(xmlDoc.DocumentElement, certFss);

            edElement.Type = CPEncryptedXml.XmlEncGost28147Url;
            XmlElement xe = edElement.GetXml();

            XmlDocument xmlDocEnc = new XmlDocument();

            xmlDocEnc.LoadXml(Properties.Resources.Source2);

            // "Правильная" замена сертификата на наш, и вставка прочих данных
            xmlDocEnc.DocumentElement.GetElementsByTagName("ds:X509Certificate").Item(0).InnerText =
                Convert.ToBase64String(certOur.RawData);
            xmlDocEnc.DocumentElement.GetElementsByTagName("xenc:CipherValue").Item(0).InnerText =
                xe.GetElementsByTagName("CipherValue").Item(0).InnerText;
            xmlDocEnc.DocumentElement.GetElementsByTagName("xenc:CipherValue").Item(1).InnerText =
                xe.GetElementsByTagName("CipherValue").Item(1).InnerText;

            // Сохраняем зашифрованный документ в файле
            xmlDocEnc.Save(filename3);

            // Отображаем файл если требуется для дебага
            if (DEBUG_STEP < 3)
            {
                foView view = new foView();
                view.Text        = filename3;
                view.xmlFileName = filename3;
                view.Show();
            }

            return(filename3);
        }
        private static XElement CreateEncryptedAssertion(string destination, string partnerIdpUrl, string userId, string appKey,
                                                         string appSecret, X509Certificate2 encryptionCert)
        {
            // Create the SAML assertion containing the secrets
            string assertionId          = "_" + Guid.NewGuid();
            string assertionIssuingTime = string.Format("{0:s}Z", DateTime.UtcNow);
            string assertionExpiryTime  = string.Format("{0:s}Z", DateTime.UtcNow.AddMinutes(2));

            XElement assertion =
                new XElement(SamlNs + "Assertion",
                             new XAttribute(XNamespace.Xmlns + "saml", SamlNs),
                             new XAttribute("Version", "2.0"),
                             new XAttribute("ID", assertionId),
                             new XAttribute("IssueInstant", assertionIssuingTime),
                             new XElement(SamlNs + "Issuer",
                                          partnerIdpUrl),
                             new XElement(SamlNs + "Subject",
                                          new XElement(SamlNs + "NameID",
                                                       userId
                                                       ),
                                          new XElement(SamlNs + "SubjectConfirmation",
                                                       new XAttribute("Method", "urn:oasis:names:tc:SAML:2.0:cm:bearer"),
                                                       new XElement(SamlNs + "SubjectConfirmationData",
                                                                    new XAttribute("Recipient", destination)
                                                                    )
                                                       )
                                          ),
                             new XElement(SamlNs + "Conditions",
                                          new XAttribute("NotOnOrAfter", assertionExpiryTime),
                                          new XElement(SamlNs + "AudienceRestriction",
                                                       new XElement(SamlNs + "Audience",
                                                                    destination
                                                                    )
                                                       )
                                          ),
                             new XElement(SamlNs + "AuthnStatement",
                                          new XAttribute("AuthnInstant", assertionIssuingTime),
                                          new XElement(SamlNs + "AuthnContext",
                                                       new XElement(SamlNs + "AuthnContextClassRef",
                                                                    "urn:oasis:names:tc:SAML:2.0:ac:classes:Password"
                                                                    )
                                                       )
                                          ),
                             new XElement(SamlNs + "AttributeStatement",
                                          new XElement(SamlNs + "Attribute",
                                                       new XAttribute("Name", "IsCertificateBasedAuthentication"),
                                                       new XAttribute("NameFormat", "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"),
                                                       new XElement(SamlNs + "AttributeValue",
                                                                    true
                                                                    )
                                                       )
                                          ),
                             new XElement(SamlNs + "AttributeStatement",
                                          new XElement(SamlNs + "Attribute",
                                                       new XAttribute("Name", "AppKey"),
                                                       new XAttribute("NameFormat", "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"),
                                                       new XElement(SamlNs + "AttributeValue",
                                                                    appKey
                                                                    )
                                                       )
                                          ),
                             new XElement(SamlNs + "AttributeStatement",
                                          new XElement(SamlNs + "Attribute",
                                                       new XAttribute("Name", "AppSecret"),
                                                       new XAttribute("NameFormat", "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"),
                                                       new XElement(SamlNs + "AttributeValue",
                                                                    appSecret
                                                                    )
                                                       )
                                          )
                             );

            // Encrypt the assertion
            XmlDocument  doc            = new XmlDocument();
            XmlElement   assertionXmlEl = doc.ReadNode(assertion.CreateReader()) as XmlElement;
            EncryptedXml eXml           = new EncryptedXml();

            if (assertionXmlEl == null)
            {
                throw new NullReferenceException("assertionXmlEl was null");
            }

            // Encrypt the element.
            EncryptedData encryptedElement = eXml.Encrypt(assertionXmlEl, encryptionCert);

            XElement encryptedAssertionXElement = XElement.Parse(encryptedElement.GetXml().OuterXml);

            // .Net adds the encryption certificate in a KeyInfo->EncryptedKey_>KeyInfo, we don't want that, so we just remove it
            encryptedAssertionXElement
            .Element(XmlDsigNs + "KeyInfo")
            .Element(XmlEncNs + "EncryptedKey")
            .Element(XmlDsigNs + "KeyInfo")
            .Remove();

            return(encryptedAssertionXElement);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Accepts SAML Response, serializes it to XML and signs using the supplied certificate
        /// </summary>
        /// <param name="Response">SAML 2.0 Response</param>
        /// <param name="SigningCert">X509 certificate</param>
        /// <returns>XML Document with computed signature</returns>
        private static XmlDocument SerializeAndSignSAMLResponse(ResponseType Response, string partnerSP)
        {
            // Set serializer and writers for action
            XmlSerializer responseSerializer = new XmlSerializer(Response.GetType());
            StringWriter  stringWriter       = new StringWriter();
            XmlWriter     responseWriter     = XmlTextWriter.Create(stringWriter, new XmlWriterSettings()
            {
                OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8
            });

            responseSerializer.Serialize(responseWriter, Response);
            responseWriter.Close();
            XmlDocument xmlResponse = new XmlDocument();

            xmlResponse.LoadXml(stringWriter.ToString());
            XmlElement elementToEncrypt = xmlResponse.GetElementsByTagName("saml:Assertion")[0] as XmlElement;

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // X.509 Certificate.
            //////////////////////////////////////////////////

            EncryptedXml eXml = new EncryptedXml();

            // Encrypt the element.
            var           certificate = SAMLConfiguration.Current.CertificateManager.GetPartnerCertificate(partnerSP);
            EncryptedData edElement   = eXml.Encrypt(elementToEncrypt, certificate);

            XmlElement encryptedAssertion = xmlResponse.CreateElement("saml2", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");

            EncryptedXml.ReplaceElement(encryptedAssertion, edElement, true);


            ////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            ////////////////////////////////////////////////////
            xmlResponse.GetElementsByTagName("Response")[0].ReplaceChild(encryptedAssertion, elementToEncrypt);

            //Get the X509 info
            XmlElement issuerSerialElement = xmlResponse.CreateElement("ds", "X509IssuerSerial", SignedXml.XmlDsigNamespaceUrl);
            XmlElement issuerNameElement   = xmlResponse.CreateElement("ds", "X509IssuerName", SignedXml.XmlDsigNamespaceUrl);

            issuerNameElement.AppendChild(xmlResponse.CreateTextNode(certificate.IssuerName.Name));
            issuerSerialElement.AppendChild(issuerNameElement);
            XmlElement serialNumberElement = xmlResponse.CreateElement("ds", "X509SerialNumber", SignedXml.XmlDsigNamespaceUrl);

            serialNumberElement.AppendChild(xmlResponse.CreateTextNode(certificate.SerialNumber));
            issuerSerialElement.AppendChild(serialNumberElement);

            // Set requested namespaces
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["EncryptedData"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["EncryptionMethod"].Prefix           = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["KeyInfo"].Prefix                    = "ds";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["EncryptedKey"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["EncryptionMethod"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["CipherData"].Prefix       = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["xenc:CipherData"]["CipherValue"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["KeyInfo"].Prefix = "ds";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["X509Data"].Prefix = "ds";
            // We don't need this for MagnaCare
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["ds:X509Data"].RemoveChild(xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["ds:X509Data"]["X509Certificate"]);
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["CipherData"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["xenc:CipherData"]["CipherValue"].Prefix = "xenc";

            //Add X509 Issuer Info
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["ds:X509Data"].AppendChild(issuerSerialElement);

            // Set the namespace for prettire and more consistent XML
            var ns = new XmlNamespaceManager(xmlResponse.NameTable);

            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            ns.AddNamespace("xenc", "http://www.w3.org/2001/04/xmlenc#");

            CertificateUtility.AppendSignatureToXMLDocument(ref xmlResponse, "#" + ((AssertionType)Response.Items[0]).ID);

            return(xmlResponse);
        }
Ejemplo n.º 25
0
        public void Encrypt_XmlNull()
        {
            EncryptedXml exml = new EncryptedXml();

            Assert.Throws <ArgumentNullException>(() => exml.Encrypt(null, "aes"));
        }
        public void Encrypt_MissingKey()
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<root />");
            EncryptedXml exml = new EncryptedXml();

            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => exml.Encrypt(doc.DocumentElement, "aes"));
        }
Ejemplo n.º 27
0
        public ActionResult Index(XmlModel model)
        {
            if (model.Action == "encrypt")
            {
                var recipientCertificate = LoadCertificate(model.RecipientThumbprint);
                var signingCertificate   = LoadCertificate(model.SenderThumbprint);
                var xmlDocument          = new XmlDocument();
                xmlDocument.LoadXml(model.PlainText);

                var elementToEncrypt = xmlDocument.GetElementsByTagName("message")[0] as XmlElement;
                var encryptedXml     = new EncryptedXml();

                // Encrypt the element.
                var encryptedElement = encryptedXml.Encrypt(elementToEncrypt, recipientCertificate);
                EncryptedXml.ReplaceElement(elementToEncrypt, encryptedElement, false);

                // Sign the document
                var signedXml = new SignedXml(xmlDocument)
                {
                    SigningKey = signingCertificate.PrivateKey
                };
                var reference = new Reference {
                    Uri = string.Empty
                };

                var transform = new XmlDsigC14NTransform();
                reference.AddTransform(transform);

                var envelope = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(envelope);
                signedXml.AddReference(reference);

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

                var xmlDigitalSignature = signedXml.GetXml();
                xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true));

                model.PlainText = "";
                model.Envelope  = XmlToString(xmlDocument);
            }
            else if (model.Action == "decrypt")
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(model.Envelope);

                // Validate the signature
                var signedXml = new SignedXml(xmlDocument);
                var nodeList  = xmlDocument.GetElementsByTagName("Signature");

                if (nodeList.Count <= 0)
                {
                    throw new Exception("No signature found.");
                }

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

                // XML signatures allows signing only parts of a document or
                // even worse, can refer to another resource that's not even
                // part of the document containing the signature. To make
                // sure that the signature we're validating is actually signing
                // the document we have to check the reference. An empty
                // reference refers to the entire enclosing document.
                if (signedXml.SignedInfo.References.Cast <Reference>().Single().Uri != "")
                {
                    throw new Exception("Signature does not refer to entire document. Validating signatures for part of the document is not supported by this code.");
                }

                AsymmetricAlgorithm signingKey;
                if (!signedXml.CheckSignatureReturningKey(out signingKey))
                {
                    throw new Exception("Invalid Signature");
                }
                else
                {
                    IEnumerable <X509Certificate2> keyInfoCertificates =
                        signedXml.KeyInfo.OfType <KeyInfoX509Data>()
                        .SelectMany(x => x.Certificates.Cast <X509Certificate2>());
                    var signingCertificate = keyInfoCertificates.FirstOrDefault(x => x.PublicKey.Key == signingKey);
                    if (signingCertificate == null)
                    {
                        throw new Exception("Signing certificate not found in KeyInfo.");
                    }
                    model.SenderSubject = signingCertificate.Subject;
                }

                var encryptedXml = new EncryptedXml(xmlDocument);
                encryptedXml.DecryptDocument();

                model.Envelope  = "";
                model.PlainText = XmlToString(xmlDocument);
            }

            ModelState.Clear();
            model.RecipientThumbprint = RecipientThumbprint;
            model.SenderThumbprint    = SenderThumbprint;
            return(View(model));
        }