public void Encrypt_DecryptDocument_AES()
        {
            XmlDocument doc = new XmlDocument();

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

            doc.LoadXml(xml);

            var aes     = CipherUtilities.GetCipher("AES/CBC/ZEROBYTEPADDING");
            var random  = new SecureRandom();
            var ivdata  = new byte[128 / 8];
            var keydata = new byte[256 / 8];

            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var param = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            EncryptedXml exml = new EncryptedXml();

            exml.AddKeyNameMapping("aes", param);
            EncryptedData ed = exml.Encrypt(doc.DocumentElement, "aes");

            doc.LoadXml(ed.GetXml().OuterXml);
            EncryptedXml exmlDecryptor = new EncryptedXml(doc);

            exmlDecryptor.AddKeyNameMapping("aes", param);
            exmlDecryptor.DecryptDocument();

            Assert.Equal(xml, doc.OuterXml);
        }
Exemple #2
0
        public void Encrypt()
        {
            var encryptionAlgorithm = new AesGcm {
                KeySize = 128
            };

            encryptionAlgorithm.GenerateKey();

            byte[] encryptedSymmetricKey = RsaOaepSha256.Encrypt(encryptionAlgorithm.Key, PublicKeyInAsn1Format);

            var encryptedKey = new EncryptedKey
            {
                Id = "ek-" + Guid.NewGuid(),
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl),
                CipherData       = new CipherData
                {
                    CipherValue = encryptedSymmetricKey
                }
            };

            var encryptedDataList = new List <EncryptedData>();

            foreach (Attachment attachment in Attachments)
            {
                attachment.Stream.Position = 0;
                Stream encryptedStream = new MemoryStream();
                encryptedStream.Write(encryptionAlgorithm.IV, 0, encryptionAlgorithm.IV.Length);

                var cryptoStream = new CryptoStream(encryptedStream, encryptionAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
                attachment.Stream.CopyTo(cryptoStream);
                cryptoStream.FlushFinalBlock();
                attachment.Stream = encryptedStream;

                var encryptedData = new EncryptedData
                {
                    Id               = "ed-" + Guid.NewGuid(),
                    Type             = "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Only",
                    EncryptionMethod = new EncryptionMethod("http://www.w3.org/2009/xmlenc11#aes128-gcm"),
                    CipherData       = new CipherData
                    {
                        CipherReference = new CipherReference("cid:" + attachment.ContentId)
                    }
                };
                encryptedData.KeyInfo.AddClause(new SecurityTokenReference(encryptedKey.Id));
                encryptedData.CipherData.CipherReference.TransformChain.Add(new AttachmentCiphertextTransform());

                encryptedDataList.Add(encryptedData);

                encryptedKey.ReferenceList.Add(new DataReference(encryptedData.Id));
            }

            var securityXml = GetSecurity() ?? CreateSecurity();

            foreach (var encryptedData in encryptedDataList)
            {
                Insert(encryptedData.GetXml(), securityXml);
            }

            Insert(encryptedKey.GetXml(), securityXml);
        }
        static void Main(string[] args)
        {
            // Create a new CipherData object.
            CipherData cd = new CipherData();

            // Assign a byte array to be the CipherValue. This is a byte array representing encrypted data.
            cd.CipherValue = new byte[8];
            // Create a new EncryptedData object.
            EncryptedData ed = new EncryptedData();

            //Add an encryption method to the object.
            ed.Id = "ED";
            ed.EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
            ed.CipherData       = cd;

            //Add key information to the object.
            KeyInfo ki = new KeyInfo();

            ki.AddClause(new KeyInfoRetrievalMethod("#EK", "http://www.w3.org/2001/04/xmlenc#EncryptedKey"));
            ed.KeyInfo = ki;

            // Create new XML document and put encrypted data into it.
            XmlDocument        doc = new XmlDocument();
            XmlElement         encryptionPropertyElement = (XmlElement)doc.CreateElement("EncryptionProperty", EncryptedXml.XmlEncNamespaceUrl);
            EncryptionProperty ep = new EncryptionProperty(encryptionPropertyElement);

            ed.AddProperty(ep);

            // Output the resulting XML information into a file.
            string path = @"c:\test\MyTest.xml";

            File.WriteAllText(path, ed.GetXml().OuterXml);
            //Console.WriteLine(ed.GetXml().OuterXml);
        }
Exemple #4
0
        public static XmlElement Encrypt(XmlElement xmlElement, SymmetricSecurityKey symmetricSecurityKey)
        {
            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());
        }
        /// <summary>
        /// Encrypt data with X509 certificate
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public override System.Xml.XmlNode Encrypt(System.Xml.XmlNode node)
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(node.OuterXml);

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

            return(eData.GetXml());
        }
Exemple #6
0
        static void Main(string[] args)
        {
            //Create a URI string.
            String uri = "http://www.woodgrovebank.com/document.xml";
            // Create a Base64 transform. The input content retrieved from the
            // URI should be Base64-decoded before other processing.
            Transform base64 = new XmlDsigBase64Transform();
            //Create a transform chain and add the transform to it.
            TransformChain tc = new TransformChain();

            tc.Add(base64);
            //Create <CipherReference> information.
            CipherReference reference = new CipherReference(uri, tc);

            // Create a new CipherData object using the CipherReference information.
            // Note that you cannot assign both a CipherReference and a CipherValue
            // to a CipherData object.
            CipherData cd = new CipherData(reference);

            // Create a new EncryptedData object.
            EncryptedData ed = new EncryptedData();

            //Add an encryption method to the object.
            ed.Id = "ED";
            ed.EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
            ed.CipherData       = cd;

            //Add key information to the object.
            KeyInfo ki = new KeyInfo();

            ki.AddClause(new KeyInfoRetrievalMethod("#EK", "http://www.w3.org/2001/04/xmlenc#EncryptedKey"));
            ed.KeyInfo = ki;

            // Create new XML document and put encrypted data into it.
            XmlDocument        doc = new XmlDocument();
            XmlElement         encryptionPropertyElement = (XmlElement)doc.CreateElement("EncryptionProperty", EncryptedXml.XmlEncNamespaceUrl);
            EncryptionProperty ep = new EncryptionProperty(encryptionPropertyElement);

            ed.AddProperty(ep);

            // Output the resulting XML information into a file.
            try
            {
                string path = @"c:\test\MyTest.xml";

                File.WriteAllText(path, ed.GetXml().OuterXml);
            }
            catch (IOException e)
            {
                Console.WriteLine("File IO error. {0}", e);
            }
        }
        public void DecryptData_CipherReference_IdUri()
        {
            XmlDocument doc = new XmlDocument();

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

            doc.LoadXml(xml);

            var random  = new SecureRandom();
            var ivdata  = new byte[128 / 8];
            var keydata = new byte[256 / 8];

            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var param = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            XmlEncryption exml        = new XmlEncryption(doc);
            XmlDecryption dexml       = new XmlDecryption(doc);
            string        cipherValue = Convert.ToBase64String(exml.EncryptData(Encoding.UTF8.GetBytes(xml), param));

            EncryptedData ed = new EncryptedData();

            ed.Type             = XmlNameSpace.Url[NS.XmlEncElementUrl];
            ed.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            ed.CipherData       = new CipherData();

            ed.CipherData.CipherReference = new CipherReference("#ID_0");
            string xslt = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match = \"/\"><xsl:value-of select=\".\" /></xsl:template></xsl:stylesheet>";
            XmlDsigXsltTransform xsltTransform = new XmlDsigXsltTransform();
            XmlDocument          xsltDoc       = new XmlDocument();

            xsltDoc.LoadXml(xslt);
            xsltTransform.LoadInnerXml(xsltDoc.ChildNodes);
            ed.CipherData.CipherReference.AddTransform(xsltTransform);
            ed.CipherData.CipherReference.AddTransform(new XmlDsigBase64Transform());


            doc.LoadXml("<root></root>");
            XmlNode encryptedDataNode = doc.ImportNode(ed.GetXml(), true);

            doc.DocumentElement.AppendChild(encryptedDataNode);
            XmlElement cipherDataByReference = doc.CreateElement("CipherData");

            cipherDataByReference.SetAttribute("ID", "ID_0");
            cipherDataByReference.InnerText = cipherValue;
            doc.DocumentElement.AppendChild(cipherDataByReference);

            string decryptedXmlString = Encoding.UTF8.GetString(dexml.DecryptData(ed, param));

            Assert.Equal(xml, decryptedXmlString);
        }
        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());
        }
Exemple #9
0
        private void Encrypt()
        {
            _encryptedStream.Position = 0;
            var algorithm = _credentials.Enc;

            var document = new XmlDocument();

            document.Load(_encryptedStream);

            var symmetric = Crypto.CreateSymmetricAlgorithm(algorithm);
            var xml       = new EncryptedXml();

            xml.Mode = symmetric.Mode;
            var cipherText = xml.EncryptData(document.DocumentElement, symmetric, false);

            var keyInfo = new KeyInfo();
            var data    = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(algorithm),
                CipherData       = new CipherData {
                    CipherValue = cipherText
                }
            };

            if (_credentials.Key is RsaSecurityKey rsa)
            {
                keyInfo.AddClause(CreateEncryptedKeyClause(symmetric.Key, rsa.Rsa, document));
            }
            else if (_credentials.Key is X509SecurityKey x509)
            {
                keyInfo.AddClause(CreateEncryptedKeyClause(symmetric.Key, x509.Certificate, document));
            }
            else if (!string.IsNullOrEmpty(_credentials.Key.KeyId))
            {
                keyInfo.AddClause(new KeyInfoName(_credentials.Key.KeyId));
            }

            if (keyInfo.Cast <KeyInfoClause>().Any())
            {
                data.KeyInfo = keyInfo;
            }

            var element = data.GetXml();

            //element = AddDigestMethodToEncryptionMethod(element, "http://www.w3.org/2000/09/xmldsig#sha1");

            WriteNode(element.CreateNavigator(), true);

            Crypto.ReleaseSymmetricAlgorithm(symmetric);
        }
Exemple #10
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);

            // Create Rijndael key.
            RijndaelManaged sessionKey = new RijndaelManaged();

            sessionKey.KeySize = 256;

            EncryptedXml eXml             = new EncryptedXml();
            XmlElement   elementToEncrypt = (XmlElement)node;

            byte[]        encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);
            EncryptedData edElement        = new EncryptedData();

            edElement.Type = EncryptedXml.XmlEncElementUrl;

            edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);

            // Encrypt the session key and add it to an EncryptedKey element.
            EncryptedKey ek = new EncryptedKey();

            byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, this.rsaKey, false);
            ek.CipherData       = new CipherData(encryptedKey);
            ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);

            // Set the KeyInfo element to specify the name of the RSA key.
            edElement.KeyInfo = new KeyInfo();
            KeyInfoName kin = new KeyInfoName();

            kin.Value = this.keyName;

            // Add the KeyInfoName element to the
            // EncryptedKey object.
            ek.KeyInfo.AddClause(kin);
            edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));

            // Add the encrypted element data to the
            // EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            // EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            return(edElement.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());
    }
Exemple #13
0
        public void DecryptData_CipherReference_IdUri()
        {
            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(doc);
                string       cipherValue = Convert.ToBase64String(exml.EncryptData(Encoding.UTF8.GetBytes(xml), aes));

                EncryptedData ed = new EncryptedData();
                ed.Type             = EncryptedXml.XmlEncElementUrl;
                ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                ed.CipherData       = new CipherData();
                // Create CipherReference: first extract node value, then convert from base64 using Transforms
                ed.CipherData.CipherReference = new CipherReference("#ID_0");
                string xslt = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match = \"/\"><xsl:value-of select=\".\" /></xsl:template></xsl:stylesheet>";
                XmlDsigXsltTransform xsltTransform = new XmlDsigXsltTransform();
                XmlDocument          xsltDoc       = new XmlDocument();
                xsltDoc.LoadXml(xslt);
                xsltTransform.LoadInnerXml(xsltDoc.ChildNodes);
                ed.CipherData.CipherReference.AddTransform(xsltTransform);
                ed.CipherData.CipherReference.AddTransform(new XmlDsigBase64Transform());

                // Create a document with EncryptedData and node with the actual cipher data (with the ID)
                doc.LoadXml("<root></root>");
                XmlNode encryptedDataNode = doc.ImportNode(ed.GetXml(), true);
                doc.DocumentElement.AppendChild(encryptedDataNode);
                XmlElement cipherDataByReference = doc.CreateElement("CipherData");
                cipherDataByReference.SetAttribute("ID", "ID_0");
                cipherDataByReference.InnerText = cipherValue;
                doc.DocumentElement.AppendChild(cipherDataByReference);

                if (PlatformDetection.IsXmlDsigXsltTransformSupported)
                {
                    string decryptedXmlString = Encoding.UTF8.GetString(exml.DecryptData(ed, aes));
                    Assert.Equal(xml, decryptedXmlString);
                }
            }
        }
Exemple #14
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);
            }
        }
        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);
        }
        public virtual XmlElement EncryptAassertion(XmlElement assertionElement)
        {
            using (var encryptionAlgorithm = new AesCryptoServiceProvider())
            {
                encryptionAlgorithm.KeySize = 256;

                var encryptedData = new EncryptedData
                {
                    Type             = EncryptedXml.XmlEncElementUrl,
                    EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url),
                    KeyInfo          = new KeyInfo()
                };
                encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(new EncryptedKey
                {
                    EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl),
                    CipherData       = new CipherData(EncryptedXml.EncryptKey(encryptionAlgorithm.Key, EncryptionPublicKey, true))
                }));

                var encryptedXml = new EncryptedXml();
                encryptedData.CipherData.CipherValue = encryptedXml.EncryptData(assertionElement, encryptionAlgorithm, false);

                return(encryptedData.GetXml());
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
//<SNIPPET3>
//<SNIPPET1>
            // Create a new CipherData object using a byte array to represent encrypted data.
            Byte[]     sampledata = new byte[8];
            CipherData cd         = new CipherData(sampledata);
//</SNIPPET1>
            // Create a new EncryptedData object.
            EncryptedData ed = new EncryptedData();

            //Add an encryption method to the object.
            ed.Id = "ED";
            ed.EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
            ed.CipherData       = cd;
//</SNIPPET3>
//<SNIPPET2>
            //Add key information to the object.
            KeyInfo ki = new KeyInfo();

            ki.AddClause(new KeyInfoRetrievalMethod("#EK", "http://www.w3.org/2001/04/xmlenc#EncryptedKey"));
            ed.KeyInfo = ki;
//</SNIPPET2>
            // Create new XML document and put encrypted data into it.
            XmlDocument        doc = new XmlDocument();
            XmlElement         encryptionPropertyElement = (XmlElement)doc.CreateElement("EncryptionProperty", EncryptedXml.XmlEncNamespaceUrl);
            EncryptionProperty ep = new EncryptionProperty(encryptionPropertyElement);

            ed.AddProperty(ep);

            // Output the resulting XML information into a file. Change the path variable to point to a directory where
            // the XML file should be written.
            string path = @"c:\test\MyTest.xml";

            File.WriteAllText(path, ed.GetXml().OuterXml);
        }
Exemple #18
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);
        }