Пример #1
0
        public void OkEncodeDecodeReplace()
        {
            // arrange
            var    encryptorDecryptor = new EncryptorDecryptor();
            var    inputFilePath      = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.config");
            var    transformFilePath  = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName, "CustomXdtTransforms.Tests", "TestAppConfigs", "TestApp.Debug.config");
            string result;

            // act
            using (var input = new XmlTransformableDocument())
                using (var transformer = new XmlTransformation(transformFilePath))
                {
                    input.Load(inputFilePath);
                    transformer.Apply(input);

                    using (var stringWriter = new StringWriter())
                        using (var xmlWriter = XmlWriter.Create(stringWriter))
                        {
                            input.WriteContentTo(xmlWriter);
                            xmlWriter.Flush();
                            result = stringWriter.ToString();

                            var xmlDoc = XDocument.Parse(result);

                            var root = xmlDoc.Root;

                            // assert
                            var ecnrypteNode2          = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted2");
                            var ecnrypteNode2Attrubute = ecnrypteNode2.Attribute("serializeAs").Value;
                            encryptorDecryptor.Decrypt(ecnrypteNode2Attrubute).Should().Be("String");
                            var encryptedNode2Value = ecnrypteNode2.Value;
                            encryptorDecryptor.Decrypt(encryptedNode2Value).Should().Be("SomeNewEncryptedValue2");
                        }
                }
        }
Пример #2
0
        public void OkEncodeDecodeAppSettings()
        {
            // arrange
            var encryptorDecryptor = new EncryptorDecryptor();

            // assert
            Configuration config      = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var           appSettings = (AppSettingsSection)config.GetSection("appSettings");

            encryptorDecryptor.Decrypt(appSettings.Settings["KeyToEncrypt1"].Value).Should().Be("PlainValue1");
            encryptorDecryptor.Decrypt(appSettings.Settings["KeyToEncrypt2"].Value).Should().Be("PlainValue2");
            appSettings.Settings["UnTouchedKey1"].Value.Should().Be("UnTouchedValue1");
            appSettings.Settings["UnTouchedKey2"].Value.Should().Be("UnTouchedValue2");
        }
Пример #3
0
        public void OkEncodeDecodeInnerText()
        {
            // arrange
            var encryptorDecryptor = new EncryptorDecryptor();

            // assert
            encryptorDecryptor.Decrypt(ConfigurationManager.ConnectionStrings["KeyToEncrypt1"].ConnectionString)
            .Should().Be("Data Source=SomeServer;Initial Catalog=EncryptDB1;Integrated Security=True");
            encryptorDecryptor.Decrypt(ConfigurationManager.ConnectionStrings["KeyToEncrypt2"].ConnectionString)
            .Should().Be("Data Source=SomeServer;Initial Catalog=EncryptDB2;Integrated Security=True");
            ConfigurationManager.ConnectionStrings["UnTouchedKey1"].ConnectionString
            .Should().Be("Data Source=SomeServer;Initial Catalog=SomeDB1;Integrated Security=True");
            ConfigurationManager.ConnectionStrings["UnTouchedKey2"].ConnectionString
            .Should().Be("Data Source=SomeServer;Initial Catalog=SomeDB2;Integrated Security=True");
        }
Пример #4
0
        void PasswordEncryptorDecryptor()
        {
            Console.WriteLine("Please enter a passphrase to use:");
            string password = Console.ReadLine();

            Console.WriteLine("Please enter your string to encrypt:");
            string plaintext = Console.ReadLine();

            Console.WriteLine("");

            Console.WriteLine("Your encrypted string is:");
            string encryptedstring = EncryptorDecryptor.Encrypt(plaintext, password);

            Console.WriteLine(encryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Your decrypted string is:");
            string decryptedstring = EncryptorDecryptor.Decrypt(encryptedstring, password);

            Console.WriteLine(decryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
Пример #5
0
        /// <inheritdoc/>
        protected override void UpdateSettingsFrom1To2(XElement root)
        {
            base.UpdateSettingsFrom1To2(root);

            // Handle protected password
            XElement oldPasswortElement  = root.Element("cloud_storage")?.Element("cloud_password");
            XElement cloudStorageAccount = root.Element("cloud_storage_account");

            if ((oldPasswortElement != null) && (cloudStorageAccount != null))
            {
                // Deobfuscate old password
                EncryptorDecryptor decryptor    = new EncryptorDecryptor("snps");
                byte[]             binaryCipher = CryptoUtils.Base64StringToBytes(oldPasswortElement.Value);
                byte[]             unprotectedBinaryPassword = decryptor.Decrypt(binaryCipher, snpsk);

                // Protect with new data protection service and add to XML
                char[] unprotectedChars           = Encoding.UTF8.GetChars(unprotectedBinaryPassword);
                byte[] unprotectedUnicodePassword = Encoding.Unicode.GetBytes(unprotectedChars);
                string protectedPassword          = _dataProtectionService.Protect(unprotectedUnicodePassword);
                cloudStorageAccount.Add(new XElement("protected_password", protectedPassword));
                CryptoUtils.CleanArray(unprotectedBinaryPassword);
                CryptoUtils.CleanArray(unprotectedChars);
                CryptoUtils.CleanArray(unprotectedUnicodePassword);
            }
        }
Пример #6
0
        public void TestEncryptionOfString()
        {
            string testSample = "this text is decrypted ok";
            string result     = EncryptorDecryptor.Encrypt(testSample);

            result = EncryptorDecryptor.Decrypt(result);
            Assert.True(result.Equals(testSample), "encryption/decryption failed");
        }
Пример #7
0
        public void ReplaceAndEncryptTest()
        {
            // arrange
            var encryptorDecryptor = new EncryptorDecryptor();

            // assert
            Configuration config      = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var           appSettings = (AppSettingsSection)config.GetSection("appSettings");

            encryptorDecryptor.Decrypt(appSettings.Settings["location"].Value).Should().Be("Canandaigua");
        }
Пример #8
0
        public void EnsureLongTimeDecryptionOfTwofishGcm()
        {
            // Ensure that a once stored cipher can always be decrypted even after changes in the liberary
            string base64Cipher = "dW5pdHRlc3QkdHdvZmlzaF9nY20kZHhMWFh4K0UrZ2MzWHdWc01rWUFxQT09JHBia2RmMiRma1BCWTdDWXp1OG5YUlJtYk9DUlp3PT0kMTAwMCRRc0ETSqDekQuBgKJ5x4Mvy02OHsivm0uJ9KchKdpGk+pmbF4Kq/EDbx9Uw54uEZUQLnK70dNKSEVtb1GyUOX1mitr";

            byte[]             cipher           = CryptoUtils.Base64StringToBytes(base64Cipher);
            EncryptorDecryptor decryptor        = new EncryptorDecryptor("unittest");
            string             decryptedMessage = CryptoUtils.BytesToString(decryptor.Decrypt(cipher, "brownie"));

            Assert.AreEqual("The brown fox jumps over the lazy 🐢🖐🏿 doc.", decryptedMessage);
        }
Пример #9
0
        public void EnsureLongTimeDecryptionOfAesGcm()
        {
            // Ensure that a once stored cipher can always be decrypted even after changes in the liberary
            string base64Cipher = "dW5pdHRlc3QkYWVzX2djbSQ0NG04QXBFU1ptcXhnYll2OE5wcWl3PT0kcGJrZGYyJGgwSDdxSGZnVFlXNzBKS3lEb0JLeFE9PSQxMDAwJJsMDjdYEYXYmcqTOFRbge6iVfWo/iny4nrIOMVuoqYak6xB/MAe53G5H3AyxiTi8OENJbi9tzZStpe3p3nlDB7l+J8=";

            byte[]             cipher           = CryptoUtils.Base64StringToBytes(base64Cipher);
            EncryptorDecryptor decryptor        = new EncryptorDecryptor("unittest");
            string             decryptedMessage = CryptoUtils.BytesToString(decryptor.Decrypt(cipher, "brownie"));

            Assert.AreEqual("The brown fox jumps over the lazy 🐢🖐🏿 doc.", decryptedMessage);
        }
Пример #10
0
        public void OkEncodeDecodeReplaceAttributeAndInnerTextByXPath()
        {
            // arrange
            var encryptorDecryptor = new EncryptorDecryptor();

            var dllPath       = Assembly.GetAssembly(typeof(TestEnvironmentForEncode)).EscapedCodeBase.TrimStart("file:///".ToArray());
            var appConfigPath = string.Format("{0}.config", dllPath);


            using (var input = new XmlTransformableDocument())
            {
                input.Load(appConfigPath);

                using (var stringWriter = new StringWriter())
                    using (var xmlWriter = XmlWriter.Create(stringWriter))
                    {
                        input.WriteContentTo(xmlWriter);
                        xmlWriter.Flush();
                        var result = stringWriter.ToString();

                        var doc = XDocument.Parse(result);

                        var root = doc.Root;

                        // assert
                        var encryptedNode1          = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted1");
                        var encryptedNode1Attribute = encryptedNode1.Attribute("serializeAs").Value;
                        encryptorDecryptor.Decrypt(encryptedNode1Attribute).Should().Be("String");
                        var encryptedNode1Value = encryptedNode1.Value;
                        encryptorDecryptor.Decrypt(encryptedNode1Value).Should().Be("SomeNewEncryptedValue1");

                        var encryptedNode2          = root.Descendants("setting").Single(x => x.Attribute("name").Value == "ExpectedEncrypted2");
                        var encryptedNode2Attribute = encryptedNode2.Attribute("serializeAs").Value;
                        encryptorDecryptor.Decrypt(encryptedNode2Attribute).Should().Be("String");
                        var encryptedNode2Value = encryptedNode2.Value;
                        encryptorDecryptor.Decrypt(encryptedNode2Value).Should().Be("EncryptedValue2");
                    }
            }
        }
Пример #11
0
        public void CryptoTestEncryptor()
        {
            EncryptorDecryptor   encryptor       = new EncryptorDecryptor("sugus");
            ICryptoRandomService randomGenerator = CommonMocksAndStubs.CryptoRandomService();
            string message = "Der schnelle Fuchs stolpert über den faulen Hund.";

            byte[] binaryMessage = CryptoUtils.StringToBytes(message);
            string password      = "******";

            byte[] cipher           = encryptor.Encrypt(binaryMessage, password, KeyDerivationCostType.Low, randomGenerator, BouncyCastleTwofishGcm.CryptoAlgorithmName);
            byte[] decryptedMessage = encryptor.Decrypt(cipher, password);
            Assert.AreEqual(binaryMessage, decryptedMessage);
        }
 private bool TryDecryptRepositoryWithTransfercode(EncryptorDecryptor encryptor, byte[] binaryCloudRepository, string transferCode, out byte[] decryptedRepository)
 {
     try
     {
         decryptedRepository = encryptor.Decrypt(binaryCloudRepository, transferCode);
         return(true);
     }
     catch (CryptoExceptionInvalidCipherFormat)
     {
         // If the downloaded repository is invalid, this is serioud and we should not continue
         throw;
     }
     catch (Exception)
     {
         // Could not decrypt with this transfercode
         decryptedRepository = null;
         return(false);
     }
 }
Пример #13
0
            /// <summary>
            /// Test the password update from Version1 in Android to Version2
            /// </summary>
            /// <param name="root"></param>
            protected override void UpdateSettingsFrom1To2(XElement root)
            {
                base.UpdateSettingsFrom1To2(root);
                const string snpsk = "53EC49B1-6600+406b;B84F-0B9CFA1D2BE1";

                // Handle protected password
                XElement oldPasswortElement  = root.Element("cloud_storage")?.Element("cloud_password");
                XElement cloudStorageAccount = root.Element("cloud_storage_account");

                if ((oldPasswortElement != null) && (cloudStorageAccount != null))
                {
                    // Deobfuscate old password
                    EncryptorDecryptor decryptor    = new EncryptorDecryptor("snps");
                    byte[]             binaryCipher = CryptoUtils.Base64StringToBytes(oldPasswortElement.Value);
                    byte[]             unprotectedBinaryPassword = decryptor.Decrypt(binaryCipher, snpsk);

                    // Protect with new data protection service and add to XML
                    string protectedPassword = _dataProtectionService.Protect(unprotectedBinaryPassword);
                    cloudStorageAccount.Add(new XElement("protected_password", protectedPassword));
                    CryptoUtils.CleanArray(unprotectedBinaryPassword);
                }
            }