<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information
//
// EncryptedXmlTest.cs
//
// Author:
//	<NAME>  <<EMAIL>>
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.


using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using Xunit;

namespace System.Security.Cryptography.Xml.Tests
{
    public class EncryptedXmlTest
    {
        private class NotSupportedSymmetricAlgorithm : SymmetricAlgorithm
        {
            public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
            {
                throw new NotImplementedException();
            }

            public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
            {
                throw new NotImplementedException();
            }

            public override void GenerateIV()
            {
                throw new NotImplementedException();
            }

            public override void GenerateKey()
            {
                throw new NotImplementedException();
            }
        }

        private static readonly Encoding DefaultEncoding = Encoding.UTF8;
        private const CipherMode DefaultCipherMode = CipherMode.CBC;
        private const PaddingMode DefaultPaddingMode = PaddingMode.ISO10126;
        private const string DefaultRecipient = "";
        private static readonly XmlResolver DefaultXmlResolver = null;
        private const int DefaultXmlDSigSearchDepth = 20;

        [Fact]
        public void Constructor_Default()
        {
            EncryptedXml encryptedXml = new EncryptedXml();
            Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
            Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
            Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
        }

        [Fact]
        public void Constructor_XmlDocument()
        {
            EncryptedXml encryptedXml = new EncryptedXml(null);
            Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
            Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
            Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
        }

        [Fact]
        public void Constructor_XmlDocumentAndEvidence()
        {
            EncryptedXml encryptedXml = new EncryptedXml(null, null);
            Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
            Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
            Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
        }

        [Theory]
        [InlineData("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample1.xml")]
        [InlineData("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample3.xml")]
        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);
            }

            EncryptedXml encxml = new EncryptedXml(doc);
            using (X509Certificate2 certificate = TestHelpers.GetSampleX509Certificate())
            using (RSA rsa = certificate.GetRSAPrivateKey())
            {
                Assert.NotNull(rsa);

                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", EncryptedXml.XmlEncNamespaceUrl);
                XmlElement el = doc.SelectSingleNode("/s:Envelope/s:Header/o:Security/e:EncryptedKey", nm) as XmlElement;
                EncryptedKey ekey = new EncryptedKey();
                ekey.LoadXml(el);
                byte[] key = rsa.Decrypt(ekey.CipherData.CipherValue, RSAEncryptionPadding.OaepSHA1);
                using (Aes aes = Aes.Create())
                {
                    aes.Key = key;
                    aes.Mode = CipherMode.CBC;
                    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, aes));
                    }
                }
            }
        }

        [Fact]
        public void Sample2()
        {
            using (Aes aes = Aes.Create())
            {
                byte[] keydata = Convert.FromBase64String("<KEY>
                aes.Mode = CipherMode.CBC;
                aes.KeySize = 256;
                aes.Key = keydata;
                aes.Padding = PaddingMode.Zeros;

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(TestHelpers.LoadResourceStream("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample2.xml"));
                EncryptedXml encxml = new EncryptedXml(doc);
                EncryptedData edata = new EncryptedData();
                edata.LoadXml(doc.DocumentElement);
                encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes));
            }
        }

        [Fact]
        public void RoundtripSample1()
        {
            using (StringWriter sw = new StringWriter())
            {

                // Encryption
                {
                    XmlDocument doc = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.LoadXml("<root>  <child>sample</child>   </root>");

                    XmlElement body = doc.DocumentElement;

                    using (Aes aes = Aes.Create())
                    {
                        byte[] keydata = Convert.FromBase64String("<KEY>
                        aes.Mode = CipherMode.CBC;
                        aes.KeySize = 256;
                        aes.IV = Convert.FromBase64String("pBUM5P03rZ6AE4ZK5EyBrw==");
                        aes.Key = keydata;
                        aes.Padding = PaddingMode.Zeros;

                        EncryptedXml exml = new EncryptedXml();
                        byte[] encrypted = exml.EncryptData(body, aes, false);
                        EncryptedData edata = new EncryptedData();
                        edata.Type = EncryptedXml.XmlEncElementUrl;
                        edata.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                        EncryptedKey ekey = new EncryptedKey();
                        // omit key encryption, here for testing
                        byte[] encKeyBytes = aes.Key;
                        ekey.CipherData = new CipherData(encKeyBytes);
                        ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
                        DataReference dr = new DataReference();<commit_msg>Add suppresion for test key data (#43060)<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information
//
// EncryptedXmlTest.cs
//
// Author:
//	<NAME>  <<EMAIL>>
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.


using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using Xunit;

namespace System.Security.Cryptography.Xml.Tests
{
    public class EncryptedXmlTest
    {
        private class NotSupportedSymmetricAlgorithm : SymmetricAlgorithm
        {
            public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
            {
                throw new NotImplementedException();
            }

            public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
            {
                throw new NotImplementedException();
            }

            public override void GenerateIV()
            {
                throw new NotImplementedException();
            }

            public override void GenerateKey()
            {
                throw new NotImplementedException();
            }
        }

        private static readonly Encoding DefaultEncoding = Encoding.UTF8;
        private const CipherMode DefaultCipherMode = CipherMode.CBC;
        private const PaddingMode DefaultPaddingMode = PaddingMode.ISO10126;
        private const string DefaultRecipient = "";
        private static readonly XmlResolver DefaultXmlResolver = null;
        private const int DefaultXmlDSigSearchDepth = 20;

        [Fact]
        public void Constructor_Default()
        {
            EncryptedXml encryptedXml = new EncryptedXml();
            Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
            Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
            Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
        }

        [Fact]
        public void Constructor_XmlDocument()
        {
            EncryptedXml encryptedXml = new EncryptedXml(null);
            Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
            Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
            Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
        }

        [Fact]
        public void Constructor_XmlDocumentAndEvidence()
        {
            EncryptedXml encryptedXml = new EncryptedXml(null, null);
            Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
            Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
            Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
            Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
            Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
            Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
        }

        [Theory]
        [InlineData("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample1.xml")]
        [InlineData("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample3.xml")]
        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);
            }

            EncryptedXml encxml = new EncryptedXml(doc);
            using (X509Certificate2 certificate = TestHelpers.GetSampleX509Certificate())
            using (RSA rsa = certificate.GetRSAPrivateKey())
            {
                Assert.NotNull(rsa);

                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", EncryptedXml.XmlEncNamespaceUrl);
                XmlElement el = doc.SelectSingleNode("/s:Envelope/s:Header/o:Security/e:EncryptedKey", nm) as XmlElement;
                EncryptedKey ekey = new EncryptedKey();
                ekey.LoadXml(el);
                byte[] key = rsa.Decrypt(ekey.CipherData.CipherValue, RSAEncryptionPadding.OaepSHA1);
                using (Aes aes = Aes.Create())
                {
                    aes.Key = key;
                    aes.Mode = CipherMode.CBC;
                    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, aes));
                    }
                }
            }
        }

        [Fact]
        public void Sample2()
        {
            using (Aes aes = Aes.Create())
            {
                aes.Mode = CipherMode.CBC;
                aes.KeySize = 256;
                // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Approved suppresion: key fot test purpose.")]
                aes.Key = Convert.FromBase64String("<KEY>
                aes.Padding = PaddingMode.Zeros;

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.Load(TestHelpers.LoadResourceStream("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample2.xml"));
                EncryptedXml encxml = new EncryptedXml(doc);
                EncryptedData edata = new EncryptedData();
                edata.LoadXml(doc.DocumentElement);
                encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes));
            }
        }

        [Fact]
        public void RoundtripSample1()
        {
            using (StringWriter sw = new StringWriter())
            {

                // Encryption
                {
                    XmlDocument doc = new XmlDocument();
                    doc.PreserveWhitespace = true;
                    doc.LoadXml("<root>  <child>sample</child>   </root>");

                    XmlElement body = doc.DocumentElement;

                    using (Aes aes = Aes.Create())
                    {
                        aes.Mode = CipherMode.CBC;
                        aes.KeySize = 256;
                        aes.IV = Convert.FromBase64String("pBUM5P03rZ6AE4ZK5EyBrw==");
                        // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Approved suppresion: key fot test purpose.")]
                        aes.Key = Convert.FromBase64String("<KEY>
                        aes.Padding = PaddingMode.Zeros;

                        EncryptedXml exml = new EncryptedXml();
                        byte[] encrypted = exml.EncryptData(body, aes, false);
                        EncryptedData edata = new EncryptedData();
                        edata.Type = EncryptedXml.XmlEncElementUrl;
                        edata.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                        EncryptedKey ekey = new EncryptedKey();
                        // omit key encryption, here for testing
                        byte[] encKeyBytes = aes.Key;
                        ekey.CipherData = new CipherData(encKeyBytes);
                        ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
                        DataReference dr = new DataReference();
{'fraction_non_alphanumeric': 0.08620892018779343, 'fraction_numerical': 0.009096244131455399, 'mean_word_length': 1.8751476294921545, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 22}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3226686', 'n_tokens_mistral': 4526, 'n_tokens_neox': 4120, 'n_words': 849}