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);

            XmlEncryption exml = new XmlEncryption();

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

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

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

            Assert.Equal(xml, doc.OuterXml);
        }
Beispiel #2
0
        private bool ProcessEncryptedDataItem(XmlElement encryptedDataElement)
        {
            if (ExceptUris.Count > 0)
            {
                for (int index = 0; index < ExceptUris.Count; index++)
                {
                    if (IsTargetElement(encryptedDataElement, (string)ExceptUris[index]))
                    {
                        return(false);
                    }
                }
            }
            EncryptedData ed = new EncryptedData();

            ed.LoadXml(encryptedDataElement);
            ICipherParameters symAlg = XmlDecryption.GetDecryptionKey(ed, NS.None);

            if (symAlg == null)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
            }
            byte[] decrypted = XmlDecryption.DecryptData(ed, symAlg);

            ReplaceEncryptedData(encryptedDataElement, decrypted);
            return(true);
        }
        public void DecryptData_CipherReference_InvalidUri()
        {
            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();
            XmlDecryption dexml = new XmlDecryption();

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

            ed.CipherData = new CipherData();
            ed.CipherData.CipherReference = new CipherReference("invaliduri");


            Action decrypt = () => dexml.DecryptData(ed, param);

            Assert.Throws <System.Security.Cryptography.CryptographicException>(decrypt);
        }
        public void DecryptEncryptedKey_Empty()
        {
            XmlDecryption ex = new XmlDecryption();
            EncryptedKey  ek = new EncryptedKey();

            Assert.Null(ex.DecryptEncryptedKey(ek));
        }
        public void DecryptEncryptedKey_KeyInfoEncryptedKey()
        {
            XmlDocument doc = new XmlDocument();

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

            doc.LoadXml(xml);

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

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

            keydata = new byte[128 / 8];
            random.NextBytes(keydata);
            var innerParam = new KeyParameter(keydata);

            keydata = new byte[192 / 8];
            random.NextBytes(keydata);
            var outerParam = new KeyParameter(keydata);

            XmlDecryption exml = new XmlDecryption(doc);

            exml.AddKeyNameMapping("aes", param);

            EncryptedKey ekey = new EncryptedKey();

            byte[] encKeyBytes = XmlEncryption.EncryptKey(outerParam.GetKey(), param);
            ekey.CipherData       = new CipherData(encKeyBytes);
            ekey.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            ekey.Id      = "Key_ID";
            ekey.KeyInfo = new KeyInfo();
            ekey.KeyInfo.AddClause(new KeyInfoName("aes"));

            KeyInfo topLevelKeyInfo = new KeyInfo();

            topLevelKeyInfo.AddClause(new KeyInfoEncryptedKey(ekey));

            EncryptedKey ekeyTopLevel = new EncryptedKey();

            byte[] encTopKeyBytes = XmlEncryption.EncryptKey(innerParam.GetKey(), outerParam);
            ekeyTopLevel.CipherData       = new CipherData(encTopKeyBytes);
            ekeyTopLevel.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            ekeyTopLevel.KeyInfo          = topLevelKeyInfo;

            doc.LoadXml(ekeyTopLevel.GetXml().OuterXml);

            byte[] decryptedKey = exml.DecryptEncryptedKey(ekeyTopLevel);
            Assert.Equal(innerParam.GetKey(), decryptedKey);

            EncryptedData eData = new EncryptedData();

            eData.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            eData.KeyInfo          = topLevelKeyInfo;
            var decryptedAlg = exml.GetDecryptionKey(eData, NS.None);

            Assert.Equal(outerParam.GetKey(), ((KeyParameter)decryptedAlg).GetKey());
        }
        public void ReplaceElement_EncryptedDataNull()
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<root />");
            Assert.Throws <ArgumentNullException>(() => XmlDecryption.ReplaceElement(doc.DocumentElement, null, false));
        }
        public static void Decrypt(XmlDocument doc, RsaKeyParameters rsaKey, string keyName)
        {
            var encrypted = new XmlDecryption(doc);

            encrypted.AddKeyNameMapping(keyName, rsaKey);
            encrypted.DecryptDocument();
        }
        public void ReplaceData_EncryptedDataNull()
        {
            XmlDecryption ex  = new XmlDecryption();
            XmlDocument   doc = new XmlDocument();

            doc.LoadXml("<root />");
            Assert.Throws <ArgumentNullException>(() => ex.ReplaceData(doc.DocumentElement, null));
        }
        public void GetDecryptionIV_InvalidAlgorithmUri()
        {
            XmlDecryption ex            = new XmlDecryption();
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.CipherData = new CipherData(new byte[16]);
            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => ex.GetDecryptionIV(encryptedData, NS.Invalid));
        }
        public void GetDecryptionIV_TripleDesUri()
        {
            XmlDecryption ex            = new XmlDecryption();
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.CipherData = new CipherData(new byte[16]);
            Assert.Equal(8, ex.GetDecryptionIV(encryptedData, NS.XmlEncTripleDESUrl).Length);
        }
        public void GetDecryptionIV_StringNullWithoutEncryptionMethod()
        {
            XmlDecryption ex            = new XmlDecryption();
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.CipherData = new CipherData(new byte[16]);
            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => ex.GetDecryptionIV(encryptedData, NS.None));
        }
        public void GetDecryptionIV_StringNull()
        {
            XmlDecryption ex            = new XmlDecryption();
            EncryptedData encryptedData = new EncryptedData();

            encryptedData.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            encryptedData.CipherData       = new CipherData(new byte[16]);
            Assert.Equal(new byte[16], ex.GetDecryptionIV(encryptedData, NS.None));
        }
        public void DecryptKey_RSA_KeyDataNull()
        {
            var keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
            var pair = keyGen.GenerateKeyPair();

            Assert.Throws <ArgumentNullException>(() => XmlDecryption.DecryptKey(null, (RsaKeyParameters)pair.Private, false));
        }
        public void GetDecryptionKey_NoEncryptionMethod()
        {
            EncryptedData edata = new EncryptedData();

            edata.KeyInfo = new KeyInfo();
            edata.KeyInfo.AddClause(new KeyInfoEncryptedKey(new EncryptedKey()));
            XmlDecryption exml = new XmlDecryption();

            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => exml.GetDecryptionKey(edata, NS.None));
        }
        public void RoundtripSample1()
        {
            using (StringWriter sw = new StringWriter())
            {
                {
                    XmlDocument doc = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.LoadXml("<root>  <child>sample</child>   </root>");

                    XmlElement body = doc.DocumentElement;

                    var aes     = CipherUtilities.GetCipher("AES/CBC/ZEROBYTEPADDING");
                    var ivdata  = Convert.FromBase64String("pBUM5P03rZ6AE4ZK5EyBrw==");
                    var keydata = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640=");
                    var param   = new ParametersWithIV(new KeyParameter(keydata), ivdata);

                    XmlEncryption exml      = new XmlEncryption();
                    byte[]        encrypted = exml.EncryptData(body, param, false);
                    EncryptedData edata     = new EncryptedData();
                    edata.Type             = XmlNameSpace.Url[NS.XmlEncElementUrl];
                    edata.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
                    EncryptedKey ekey = new EncryptedKey();

                    byte[] encKeyBytes = keydata;
                    ekey.CipherData       = new CipherData(encKeyBytes);
                    ekey.EncryptionMethod = new EncryptionMethod(NS.XmlEncRSA15Url);
                    DataReference dr = new DataReference();
                    dr.Uri = "_0";
                    ekey.AddReference(dr);
                    edata.KeyInfo.AddClause(new KeyInfoEncryptedKey(ekey));
                    ekey.KeyInfo.AddClause(new RsaKeyValue());
                    edata.CipherData.CipherValue = encrypted;
                    XmlDecryption.ReplaceElement(doc.DocumentElement, edata, false);
                    doc.Save(new XmlTextWriter(sw));
                }


                {
                    var aes     = CipherUtilities.GetCipher("AES/CBC/ZEROBYTEPADDING");
                    var random  = new SecureRandom();
                    var ivdata  = new byte[aes.GetBlockSize()];
                    var keydata = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640=");
                    random.NextBytes(ivdata);
                    var param = new ParametersWithIV(new KeyParameter(keydata), ivdata);

                    XmlDocument doc = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.LoadXml(sw.ToString());
                    XmlDecryption encxml = new XmlDecryption(doc);
                    EncryptedData edata  = new EncryptedData();
                    edata.LoadXml(doc.DocumentElement);
                    encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, param));
                }
            }
        }
        public void RsaDecryption(string resourceName)
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string originalXml;

            using (Stream stream = TestHelpers.LoadResourceStream(resourceName))
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    originalXml = streamReader.ReadToEnd();
                    doc.LoadXml(originalXml);
                }

            XmlDecryption encxml      = new XmlDecryption(doc);
            var           certificate = TestHelpers.GetSampleX509Certificate();
            var           rsaKey      = certificate.Item2 as RsaKeyParameters;

            Assert.NotNull(rsaKey);

            XmlNamespaceManager nm = new XmlNamespaceManager(doc.NameTable);

            nm.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
            nm.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nm.AddNamespace("e", XmlNameSpace.Url[NS.XmlEncNamespaceUrl]);
            XmlElement   el   = doc.SelectSingleNode("/s:Envelope/s:Header/o:Security/e:EncryptedKey", nm) as XmlElement;
            EncryptedKey ekey = new EncryptedKey();

            ekey.LoadXml(el);

            var rsa = CipherUtilities.GetCipher("RSA//OAEPPADDING");

            rsa.Init(false, rsaKey);
            byte[] key = rsa.DoFinal(ekey.CipherData.CipherValue);

            var aes    = CipherUtilities.GetCipher("AES/CBC/PKCS7PADDING");
            var random = new SecureRandom();
            var ivdata = new byte[aes.GetBlockSize()];

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

            List <XmlElement> elements = new List <XmlElement>();

            foreach (XmlElement encryptedDataElement in doc.SelectNodes("//e:EncryptedData", nm))
            {
                elements.Add(encryptedDataElement);
            }
            foreach (XmlElement encryptedDataElement in elements)
            {
                EncryptedData edata = new EncryptedData();
                edata.LoadXml(encryptedDataElement);
                encxml.ReplaceData(encryptedDataElement, encxml.DecryptData(edata, param));
            }
        }
        public void Constructor_XmlDocument()
        {
            XmlDecryption encryptedXml = new XmlDecryption(null);

            Assert.Equal(DefaultEncoding, encryptedXml.GetEncoding());
            Assert.Equal(DefaultCipherMode, encryptedXml.GetMode());
            Assert.Equal(DefaultPaddingMode, encryptedXml.GetPadding());
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.GetResolver());
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.GetXmlDSigSearchDepth());
        }
        public void EncryptKey_RSA_UseOAEP()
        {
            byte[] data   = Encoding.ASCII.GetBytes("12345678");
            var    keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
            var pair = keyGen.GenerateKeyPair();

            byte[] encryptedData = XmlEncryption.EncryptKey(data, (RsaKeyParameters)pair.Public, true);
            byte[] decryptedData = XmlDecryption.DecryptKey(encryptedData, (RsaKeyParameters)pair.Private, true);
            Assert.Equal(data, decryptedData);
        }
        public void DecryptKey_KeyNull()
        {
            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);

            Assert.Throws <ArgumentNullException>(() => XmlDecryption.DecryptKey(null, new KeyParameter(keydata)));
        }
        public void ReplaceElement_ContentTrue()
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<root />");
            EncryptedData edata = new EncryptedData();

            edata.CipherData.CipherValue = new byte[16];
            XmlDecryption.ReplaceElement(doc.DocumentElement, edata, true);
            Assert.Equal("root", doc.DocumentElement.Name);
            Assert.Equal("EncryptedData", doc.DocumentElement.FirstChild.Name);
        }
        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);
        }
Beispiel #22
0
        private void ReplaceEncryptedData(XmlElement encryptedDataElement, byte[] decrypted)
        {
            XmlNode parent = encryptedDataElement.ParentNode;

            if (parent.NodeType == XmlNodeType.Document)
            {
                parent.InnerXml = XmlDecryption.GetEncoding().GetString(decrypted);
            }
            else
            {
                XmlDecryption.ReplaceData(encryptedDataElement, decrypted);
            }
        }
        public void DecryptData_EncryptedDataNull()
        {
            XmlDecryption ex      = new XmlDecryption();
            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);

            Assert.Throws <ArgumentNullException>(() => ex.DecryptData(null, param));
        }
        private static void Decrypt(XmlDocument doc, ICipherParameters key)
        {
            var encryptedElement = (XmlElement)doc.GetElementsByTagName("EncryptedData")[0];

            var encryptedData = new EncryptedData();

            encryptedData.LoadXml(encryptedElement);

            var encryptedXml = new XmlDecryption();

            byte[] rgbOutput = encryptedXml.DecryptData(encryptedData, key);

            encryptedXml.ReplaceData(encryptedElement, rgbOutput);
        }
        private static void EncryptElement(XmlDocument doc, string elementName, ICipherParameters key)
        {
            var elementToEncrypt = (XmlElement)doc.GetElementsByTagName(elementName)[0];

            var encryptedXml  = new XmlEncryption();
            var encryptedData = new EncryptedData()
            {
                Type             = XmlNameSpace.Url[NS.XmlEncElementUrl],
                EncryptionMethod = new EncryptionMethod(GetEncryptionMethodName(key))
            };

            encryptedData.CipherData.CipherValue = encryptedXml.EncryptData(elementToEncrypt, key, false);

            XmlDecryption.ReplaceElement(elementToEncrypt, encryptedData, false);
        }
        public void EncryptKey_AES()
        {
            var random  = new SecureRandom();
            var keydata = new byte[256 / 8];

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

            byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678");

            byte[] encryptedKey = XmlEncryption.EncryptKey(key, param);

            Assert.NotNull(encryptedKey);
            Assert.Equal(key, XmlDecryption.DecryptKey(encryptedKey, param));
        }
        public void Sample2()
        {
            var aes     = CipherUtilities.GetCipher("AES/CBC/ZEROBYTEPADDING");
            var random  = new SecureRandom();
            var ivdata  = new byte[aes.GetBlockSize()];
            var keydata = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640=");

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

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.Load(TestHelpers.LoadResourceStream("Org.BouncyCastle.Crypto.Xml.Tests.EncryptedXmlSample2.xml"));
            XmlDecryption encxml = new XmlDecryption(doc);
            EncryptedData edata  = new EncryptedData();

            edata.LoadXml(doc.DocumentElement);
            encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, param));
        }
        public void GetDecryptionKey_CarriedKeyName()
        {
            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);

            keydata = new byte[128 / 8];
            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var innerParam = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            EncryptedData edata = new EncryptedData();

            edata.KeyInfo = new KeyInfo();
            edata.KeyInfo.AddClause(new KeyInfoName("aes"));

            EncryptedKey ekey = new EncryptedKey();

            byte[] encKeyBytes = XmlEncryption.EncryptKey(((KeyParameter)innerParam.Parameters).GetKey(), (KeyParameter)param.Parameters);
            ekey.CipherData       = new CipherData(encKeyBytes);
            ekey.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            ekey.CarriedKeyName   = "aes";
            ekey.KeyInfo          = new KeyInfo();
            ekey.KeyInfo.AddClause(new KeyInfoName("another_aes"));

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(ekey.GetXml().OuterXml);

            XmlDecryption exml = new XmlDecryption(doc);

            exml.AddKeyNameMapping("another_aes", param);
            var decryptedAlg = exml.GetDecryptionKey(edata, NS.XmlEncAES256Url);

            Assert.IsType <KeyParameter>(decryptedAlg);
            Assert.Equal(((KeyParameter)innerParam.Parameters).GetKey(), ((KeyParameter)decryptedAlg).GetKey());
        }
Beispiel #29
0
        private XmlDocument GetTransformedOutput(XmlDocument doc, string nodeToEncrypt)
        {
            var aes     = CipherUtilities.GetCipher("AES/CBC/PKCS7");
            var random  = new SecureRandom();
            var keyData = new byte[aes.GetBlockSize()];
            var ivData  = new byte[aes.GetBlockSize()];

            random.NextBytes(ivData);
            random.NextBytes(keyData);
            var key = new ParametersWithIV(new KeyParameter(keyData), ivData);

            var encryptedXml = new XmlEncryption();

            encryptedXml.AddKeyNameMapping("aes", key);

            XmlElement    elementToEncrypt = (XmlElement)doc.DocumentElement.SelectSingleNode(nodeToEncrypt);
            EncryptedData encryptedData    = encryptedXml.Encrypt(elementToEncrypt, "aes");

            XmlDecryption.ReplaceElement(elementToEncrypt, encryptedData, false);

            XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable);

            xmlNamespaceManager.AddNamespace("enc", XmlNameSpace.Url[NS.XmlEncNamespaceUrl]);
            XmlElement encryptedNode = (XmlElement)doc.DocumentElement.SelectSingleNode("//enc:EncryptedData", xmlNamespaceManager);

            encryptedNode.SetAttribute("ID", "#_0");

            transform.LoadInput(doc);

            var dencryptedXml = new XmlDecryption();

            dencryptedXml.AddKeyNameMapping("aes", key);

            transform.XmlDecryption = dencryptedXml;
            XmlDocument transformedDocument = (XmlDocument)transform.GetOutput();

            transform.XmlDecryption = null;

            return(transformedDocument);
        }
        private static void Encrypt(XmlDocument doc, string elementName, string encryptionElementID, RsaKeyParameters rsaKey, string keyName, bool useOAEP)
        {
            var elementToEncrypt = (XmlElement)doc.GetElementsByTagName(elementName)[0];

            var sessionKeyData = EncryptingAndDecryptingSymmetric.GenerateBlock(256);
            var sessionKeyIV   = EncryptingAndDecryptingSymmetric.GenerateBlock(128);
            var sessionKey     = new ParametersWithIV(new KeyParameter(sessionKeyData), sessionKeyIV);

            var encryptedKey = new EncryptedKey()
            {
                CipherData       = new CipherData(XmlEncryption.EncryptKey(sessionKeyData, rsaKey, useOAEP)),
                EncryptionMethod = new EncryptionMethod(useOAEP ? NS.XmlEncRSAOAEPUrl : NS.XmlEncRSA15Url)
            };

            encryptedKey.AddReference(new DataReference()
            {
                Uri = "#" + encryptionElementID
            });

            var encryptedData = new EncryptedData()
            {
                Type = XmlNameSpace.Url[NS.XmlEncElementUrl],
                Id   = encryptionElementID,

                EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url)
            };

            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));
            encryptedKey.KeyInfo.AddClause(new KeyInfoName()
            {
                Value = keyName
            });

            var encryptedXml = new XmlEncryption();

            encryptedData.CipherData.CipherValue = encryptedXml.EncryptData(elementToEncrypt, sessionKey, false);

            XmlDecryption.ReplaceElement(elementToEncrypt, encryptedData, false);
        }