Exemplo n.º 1
0
        public void TestMethod13()
        {
            var          se        = new SymmetricEncryption("爱我中华爱我中华1574551¥#@54633", 0);
            const string sourceStr = "爱我中华爱";

            Assert.AreNotEqual(sourceStr, se.Decrypt(se.Encrypt(sourceStr, Encoding.UTF8), Encoding.Unicode));
            Assert.AreEqual(sourceStr, se.Decrypt(se.Encrypt(sourceStr, Encoding.Unicode), Encoding.Unicode));
        }
Exemplo n.º 2
0
        public void TestMethod12()
        {
            var          se         = new SymmetricEncryption("爱我中华爱我中华1574551¥#@54633", 0);
            const string sourceStr  = "爱我中华爱";
            var          targetStr  = se.Encrypt(sourceStr);
            var          targetStr2 = se.Encrypt(sourceStr, Encoding.ASCII);

            Assert.AreNotEqual(targetStr, targetStr2);
            Assert.AreEqual(sourceStr, se.Decrypt(targetStr));
        }
        public void EncryptWithTripleDES_Should_ReturnExpectedResult_When_ProvidedKeysAndInitializationVector()
        {
            // Arrange
            var key    = new EncryptionData("SecretKey");
            var vector = new EncryptionData("InitializationVector");

            var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
            {
                InitializationVector = vector
            };

            var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
            {
                InitializationVector = vector
            };

            // Act
            var encrypted = e1.Encrypt(_targetData, key);
            var decrypted = e2.Decrypt(encrypted, key);

            // -- the data will be padded to the encryption block size, so we need to trim it back down.
            var actual = decrypted.Text.Substring(0, _targetData.Bytes.Length);

            // Assert
            Assert.Equal(_targetString, actual);
        }
        public void Encrypted_Data_Differs_From_Raw_data()
        {
            byte[] rawData = Random.GetNumbers(256);

            byte[] encryptedData = SymmetricEncryption.Encrypt(rawData, key, iv);
            CollectionAssert.AreNotEqual(rawData, encryptedData);
        }
Exemplo n.º 5
0
        private async void ClickSetting()
        {
            if (VerificationAuth.IsValidPassword(newPasswordBox.Password, newPasswordConfirmBox.Password)) //Check if both password match.
            {
                progressSetting.IsActive     = true;
                backgroundWaiting.Visibility = Visibility.Visible;
                string ActualPassword = encryptionProvider.Decrypt(connectedUser.password);
                if (passwordActualBox.Password == ActualPassword)
                {
                    connectedUser.password = encryptionProvider.Encrypt(newPasswordBox.Password);//Encrypt the password.
                    await apiConnect.PostAsJsonAsync(connectedUser, "http://localhost/api/auth/changepassword.php");

                    progressSetting.IsActive     = false;
                    backgroundWaiting.Visibility = Visibility.Collapsed;
                    ChangePasswordContentDialog dialog = new ChangePasswordContentDialog(parameter.rootFrame, parameter.connectedUser);
                    await dialog.ShowAsync();
                }
                else
                {
                    progressSetting.IsActive     = false;
                    backgroundWaiting.Visibility = Visibility.Collapsed;
                    VerificationAuth.AnimationErrorTextBox(passwordActualBox, errorSecondPasswordBoxStoryboard, errorSecondPasswordBoxColor, btnChange); //Launch error animation on textMail TextBox.
                    errorActualPassword.Text = "Your actual password do not match.";
                }
            }
            else
            {
                progressSetting.IsActive     = false;
                backgroundWaiting.Visibility = Visibility.Collapsed;
                VerificationAuth.AnimationErrorTextBox(newPasswordBox, errorFirstPasswordBoxStoryboard, errorFirstPasswordBoxColor, btnChange);          //Launch error animation on passwordBox PasswordBox.
                VerificationAuth.AnimationErrorTextBox(newPasswordConfirmBox, errorSecondPasswordBoxStoryboard, errorSecondPasswordBoxColor, btnChange); //Launch error animation on passwordConfirmBox PasswordBox.
                errorNewPassword.Text = "The new passwords do not match.";
            }
        }
Exemplo n.º 6
0
        public void Encrypt_Progress_Test()
        {
            #region Arrange

            var pwd      = Guid.NewGuid().ToString();
            var filename = Guid.NewGuid().ToString();

            var progressValues = new List <double>();

            var multiplier = 10;

            #endregion

            #region Act

            using (var input = new MemoryStream(new byte[SymmetricEncryption.BufferSize * multiplier]))
                using (var output = new MemoryStream())
                {
                    SymmetricEncryption.Encrypt(input, output, pwd, filename, d => { progressValues.Add(d); }, () => false);
                }

            #endregion

            #region Assert

            Assert.That(progressValues.Count, Is.EqualTo(multiplier));
            Assert.That(progressValues, Is.Ordered);
            Assert.That(progressValues, Is.Unique);
            Assert.That(progressValues, Has.None.GreaterThan(100));
            Assert.That(progressValues, Has.None.LessThan(0));

            #endregion
        }
Exemplo n.º 7
0
        public void EncryptDecryptTest_Stream()
        {
            string decryptionKey = "7A008A8C4AD363C77E88F638DC32FFD8";
            string algorithmName = "Rijndael";

            string sourceFileName    = "Source.txt";
            string encryptedFileName = "Encrypted.enc";
            string decryptedFileName = "Decrypted.txt";

            string text = "これは、SymmetricEncryption クラスのテストです。";

            File.WriteAllText(sourceFileName, text, Encoding.UTF8);

            using (Stream input = File.OpenRead(sourceFileName))
                using (Stream output = File.OpenWrite(encryptedFileName))
                {
                    SymmetricEncryption.Encrypt(input, output, decryptionKey, algorithmName);
                }

            using (Stream input = File.OpenRead(encryptedFileName))
                using (Stream output = File.OpenWrite(decryptedFileName))
                {
                    SymmetricEncryption.Decrypt(input, output, decryptionKey, algorithmName);
                }

            CollectionAssert.AreEqual(File.ReadAllBytes(sourceFileName), File.ReadAllBytes(decryptedFileName));
        }
Exemplo n.º 8
0
        public void EncryptAndDecrypt_UseFromStreamTest()
        {
            #region Arrange

            var data = Random.CreateData(128 / 8);
            File.WriteAllBytes(this.InputFile, data);

            var pwd      = Guid.NewGuid().ToString();
            var filename = Guid.NewGuid().ToString();
            var key      = Random.CreateData(512 / 8);

            #endregion

            #region Act

            Exception ex;
            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.OpenWrite(this.OutputFile))
                {
                    ex = Assert.Throws <Exception>(() => SymmetricEncryption.Encrypt(input, output, key, filename));
                }

            #endregion

            #region Assert

            Assert.That(ex.Message, Is.EqualTo("Strean must support read and write operations"));

            #endregion
        }
Exemplo n.º 9
0
        public void DerivedKeys_Should_ProduceTheSameKeyProvidedWithSamePassword()
        {
            // Arrange
            var vector = new EncryptionData("sdfasdfasdfasdf");
            var k1     = new DerivedKey(_password);
            var ek1    = new EncryptionData(k1.GetBytes(25));

            var k2  = new DerivedKey(_password);
            var ek2 = new EncryptionData(k2.GetBytes(25));

            var e1 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
            {
                InitializationVector = vector
            };

            var e2 = new SymmetricEncryption(SymmetricEncryption.Provider.TripleDES)
            {
                InitializationVector = vector
            };

            // Act
            var encrypted = e1.Encrypt(new EncryptionData(_plainText), ek1);
            var decrypted = e2.Decrypt(encrypted, ek2);

            // Assert
            Assert.Equal(_plainText, decrypted.Text);
        }
Exemplo n.º 10
0
        private static string EncryptUserName(string userName)
        {
            string originalKey = ConfigurationManager.AppSettings["SecretKey"];

            byte[] Key = Encoding.Unicode.GetBytes(originalKey);
            return(SymmetricEncryption.Encrypt(userName, originalKey));
        }
Exemplo n.º 11
0
        public string GetCallPdfUrl(int callId, bool pdf = false, int?stationId = null)
        {
            try
            {
                string encryptedQuery = "";

                if (!stationId.HasValue && !pdf)
                {
                    encryptedQuery = WebUtility.UrlEncode(SymmetricEncryption.Encrypt(callId.ToString(), Config.SystemBehaviorConfig.ExternalLinkUrlParamPassphrase));
                }
                else
                {
                    string type    = pdf ? "pdf" : "web";
                    string station = stationId.HasValue ? stationId.Value.ToString() : "0";

                    encryptedQuery = WebUtility.UrlEncode(SymmetricEncryption.Encrypt($"{callId.ToString()}|{type}|{station}", Config.SystemBehaviorConfig.ExternalLinkUrlParamPassphrase));
                }


                return($"{Config.SystemBehaviorConfig.ResgridBaseUrl}/User/Dispatch/CallExportPdf?query={encryptedQuery}");
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                return(String.Empty);
            }
        }
Exemplo n.º 12
0
        public void Encrypt_Cancel_Test()
        {
            #region Arrange

            var pwd      = Guid.NewGuid().ToString();
            var filename = Guid.NewGuid().ToString();

            int progressCounter = 0;

            #endregion

            #region Act

            using (var input = new MemoryStream(new byte[SymmetricEncryption.BufferSize * 10]))
                using (var output = new MemoryStream())
                {
                    SymmetricEncryption.Encrypt(input, output, pwd, filename, d => progressCounter++, () => true);
                }

            #endregion

            #region Assert

            Assert.That(progressCounter, Is.EqualTo(0));

            #endregion
        }
Exemplo n.º 13
0
        /// <summary>
        /// Get a Nessus token created from the Basic authorization token
        /// </summary>
        /// <param name="basicToken">token from the Basic authorization</param>
        /// <returns>Nessus token if valid basic token, null otherwise</returns>
        public string GetNessusToken(string basicToken)
        {
            if (string.IsNullOrEmpty(basicToken))
            {
                return(null);
            }

            // Ensure Basic authorization has username:password
            string username = basicToken.Substring(0, basicToken.IndexOf(":"));
            string password = basicToken.Substring(basicToken.IndexOf(":") + 1);

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            // Create a Nessus token from the basic token and a timestamp in case we want to timeout user authorizations
            string plainText = string.Format("{0}:{1}", basicToken, DateTime.Now.ToString("HH:mm:ss.ffffff"));
            string token     = SymmetricEncryption.Encrypt(plainText);

            if (!validNessusTokens.TryAdd(token, token))
            {
                return(null);
            }

            return(token);
        }
Exemplo n.º 14
0
        public void TestMethod11()
        {
            var          se        = new SymmetricEncryption("爱我中华爱我中华1574551¥#@54633", 0);
            const string sourceStr = "humin123";
            var          targetStr = se.Encrypt(sourceStr);

            Assert.AreEqual(sourceStr, se.Decrypt(targetStr));
        }
        public void Can_Encrypt_Data()
        {
            byte[] rawData = Random.GetNumbers(256);

            byte[] encryptedData = SymmetricEncryption.Encrypt(rawData, key, iv);
            Assert.NotNull(encryptedData);
            CollectionAssert.IsNotEmpty(encryptedData);
        }
Exemplo n.º 16
0
        public void TestMethod5()
        {
            var          se        = new SymmetricEncryption("12345678", "87654321", SymmetricAlgorithmType.TripleDES);
            const string sourceStr = "humin123";
            var          targetStr = se.Encrypt(sourceStr);

            Assert.AreEqual(sourceStr, se.Decrypt(targetStr));
        }
Exemplo n.º 17
0
 public void OddLengthEncryptionKeyTest()
 {
     Assert.Throws(typeof(ArgumentOutOfRangeException), () =>
     {
         var encryption = new SymmetricEncryption("12312");
         encryption.Encrypt("A", Encoding.UTF8);
     });
 }
Exemplo n.º 18
0
        public void TestMethod1()
        {
            const string sourceStr = "humin123";
            var          se        = new SymmetricEncryption("jay123456");
            var          targetStr = se.Encrypt(sourceStr);

            Assert.AreEqual(sourceStr, se.Decrypt(targetStr));
        }
Exemplo n.º 19
0
        public void Encrypt_Wrong()
        {
            var data = "P@ssw0rd";
            var key  = SymmetricEncryption.GenerateKeyBase64();
            var key2 = SymmetricEncryption.GenerateKeyBase64();

            var encrypted  = SymmetricEncryption.Encrypt(data, key);
            var decrypted2 = SymmetricEncryption.Decrypt(encrypted, key2);
        }
        public void Encryption_With_Different_IV_Returns_Different_Result()
        {
            byte[] rawData = Random.GetNumbers(256);

            byte[] encryptedData1 = SymmetricEncryption.Encrypt(rawData, key, iv);
            byte[] encryptedData2 = SymmetricEncryption.Encrypt(rawData, key, Random.GetNumbers(16));

            CollectionAssert.AreNotEqual(encryptedData1, encryptedData2);
        }
Exemplo n.º 21
0
        public void OnPasswordConfirmation(byte[] hashKey)
        {
            var websiteManager    = new WebsiteManager();
            var encryptedPassword = SymmetricEncryption.Encrypt(Convert.ToBase64String(hashKey), WebsitePasswordTxtBox.Password);

            websiteManager.Create(UserId, WebsiteNameTxtBox.Text, encryptedPassword, UsernameTxtBox.Text, UrlTxtBox.Text);
            _mainWindow.PopulateWebsiteList();
            _mainWindow.DetailsWindow.Content = new BlankPage();
        }
Exemplo n.º 22
0
        public static string Create(string userName, int departmentId)
        {
            var painText      = string.Join("|", new[] { userName, departmentId.ToString(), DateTime.UtcNow.AddMonths(Config.SystemBehaviorConfig.APITokenMonthsTTL).ToShortDateString() });
            var encryptedText = SymmetricEncryption.Encrypt(painText, Config.SystemBehaviorConfig.ApiTokenEncryptionPassphrase);
            var buffer        = Encoding.ASCII.GetBytes(encryptedText);
            var authHeader    = Convert.ToBase64String(buffer);

            return(authHeader);
        }
        public void PlainTextIsDifferentFromEncrypted()
        {
            var salt = Hash.GenerateSalt(20);
            var key  = Hash.GenerateHash(Encoding.ASCII.GetBytes("Password123"), salt, 1000, 16);

            var text          = "JustSomePlainText";
            var encrpytedText = SymmetricEncryption.Encrypt(Convert.ToBase64String(key), text);

            Assert.AreEqual(true, text != encrpytedText);
        }
        public void Encrypted_Data_Can_Be_Decrypted()
        {
            byte[] rawData = Random.GetNumbers(256);

            byte[] encryptedData = SymmetricEncryption.Encrypt(rawData, key, iv);

            byte[] decryptedData = SymmetricEncryption.Decrypt(encryptedData, key, iv);

            CollectionAssert.AreEqual(rawData, decryptedData);
        }
Exemplo n.º 25
0
        public void TestMethod6()
        {
            var          se         = new SymmetricEncryption("12345678", "87654321");
            const string sourceStr  = "humin123";
            var          targetStr  = se.Encrypt(sourceStr);
            var          se2        = new SymmetricEncryption("12345678", "87654321", SymmetricAlgorithmType.AES);
            var          targetStr2 = se2.Encrypt(sourceStr);

            Assert.AreEqual(targetStr, targetStr2);
        }
Exemplo n.º 26
0
        public void Encrypt_Old_Equals()
        {
            var data = "P@ssw0rd";
            var key  = SymmetricEncryption.GenerateKeyBase64();

            var encrypted  = SymmetricEncryption.Encrypt(data, key);
            var encrypted2 = SymmetricEncryption_Old.Encrypt(data, key);

            Assert.AreEqual(encrypted, encrypted2);
        }
Exemplo n.º 27
0
        private static void ShowSymmetricEncryption(SymmetricEncryption.ServiceProvider algorithm, string inputText)
        {
            string encryptedText = SymmetricEncryption.Encrypt(algorithm, inputText, password, salt);
            string decryptedText = SymmetricEncryption.Decrypt(algorithm, encryptedText, password, salt);

            Console.WriteLine("---  Encryption Algorithm used {0}  ---", algorithm);
            Console.WriteLine("Encrypted Text:{0}", encryptedText);
            Console.WriteLine("Decrypted Text:{0}", decryptedText);
            Console.WriteLine();
        }
        public void TheWrongKeyWillNotDecryptTheData()
        {
            var salt = Hash.GenerateSalt(20);
            var key1 = Hash.GenerateHash(Encoding.ASCII.GetBytes("Password1"), salt, 1000, 16);
            var key2 = Hash.GenerateHash(Encoding.ASCII.GetBytes("Password2"), salt, 1000, 16);

            var text          = "JustSomePlainText";
            var encrpytedText = SymmetricEncryption.Encrypt(Convert.ToBase64String(key1), text);

            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => SymmetricEncryption.Decrypt(Convert.ToBase64String(key2), encrpytedText));
        }
        public void NoMatterTheKeyTheDataCanBeEncrypted(string MasterPassword)
        {
            var salt = Hash.GenerateSalt(20);
            var key  = Hash.GenerateHash(Encoding.ASCII.GetBytes(MasterPassword), salt, 1000, 16);

            var text          = "JustSomePlainText";
            var encrpytedText = SymmetricEncryption.Encrypt(Convert.ToBase64String(key), text);
            var plainText     = SymmetricEncryption.Decrypt(Convert.ToBase64String(key), encrpytedText);

            Assert.AreEqual(text, plainText);
        }
Exemplo n.º 30
0
        public void CanEncryptDecrypt()
        {
            var privateKey = "this is my encryption key!!";

            byte[] original = Encoding.UTF8.GetBytes("Hello world");

            var encrypted = SymmetricEncryption.Encrypt(original, privateKey);
            var decrypted = SymmetricEncryption.Decrypt(encrypted, privateKey);

            Assert.Equal(original, decrypted);
        }