Exemple #1
0
        /// <summary>
        /// Saves or updates in the configuration (in appSettings) the key and value passed.
        /// </summary>
        /// <param name="key">Key to use to save the value</param>
        /// <param name="value">Value to be saved (it will be trimmed)</param>
        /// <param name="encript">True if the value must be encrypted, false otherwise</param>
        public static void SetKey(string key, string value, bool encript = false)
        {
            //Open the configuration
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                //Encrypt the value if needed
                string strValue = value;
                if (encript)
                {
                    using (CryptoUtilities crypto = new CryptoUtilities())
                    {
                        strValue = crypto.EncryptToString(value);
                    }
                }

                //Add the key-value in the configuration
                config.AppSettings.Settings.Remove(key);
                config.Save(ConfigurationSaveMode.Modified);
                config.AppSettings.Settings.Add(key, strValue.Trim());
                config.Save(ConfigurationSaveMode.Modified);

                //Refresh the configuration to take the new key-value
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                throw new SystemConfigurationException(ex, "The key {0} could not be saved in the configuration", key);
            }
        }
        public bool CreateAndSaveAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            byte[] salt           = CryptoUtilities.Get256BitSalt();
            byte[] hashedPassword = CryptoUtilities.GetHash(CryptoUtilities.StringToByteArray(password), salt);

            AccountStore store = AccountStore.Create();

            if (GetAccountFromStore(store, username) != null)
            {
                return(false);
            }

            Account account = new Account(username);

            account.Properties.Add(key_password, Convert.ToBase64String(hashedPassword));
            account.Properties.Add(key_salt, Convert.ToBase64String(salt));
            account.Properties.Add(key_keymaterial, Convert.ToBase64String(
                                       CryptoUtilities.GetAES256KeyMaterial()));

            store.Save(account, service_id);

            return(true);
        }
Exemple #3
0
        /// <summary>
        /// Returns from the configuration the connection string passed by parameter.
        /// </summary>
        /// <param name="name">Name of the connection string passed by parameter. False by default</param>
        /// <param name="isEncripted">True if the connection string is encrypted, false otherwise</param>
        /// <returns>The connection string passed by parameter</returns>
        public static string GetConnectionString(string name, bool isEncripted = false)
        {
            string connectionString = string.Empty;

            //Open the configuration
            try
            {
                //Get the connection string from the configuration
                connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;

                if (connectionString == null)
                {
                    throw new SystemConfigurationException("The connection string {0} could not be read from the configuration", name);
                }

                //Decrypt it if needed
                if (isEncripted && !string.IsNullOrWhiteSpace(connectionString))
                {
                    using (CryptoUtilities crypto = new CryptoUtilities())
                    {
                        connectionString = crypto.DecryptString(connectionString.Trim());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SystemConfigurationException(ex, "The connection string {0} could not be read from the configuration", name);
            }

            //Return the connection string
            return(connectionString);
        }
        public async Task TestInvalidCaseAsync()
        {
            // arrange
            var obj = new {
                username = "******",
                password = "******"
            };

            var repository = new Mock <IRepository>();
            var settings   = new ApplicationSettings();

            var set = TestUtilities.CreateDbSetMock(new List <User> {
                new User {
                    Username = obj.username, Password = CryptoUtilities.CreateHash(obj.password)
                },
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(set.Object);

            var validationService = new ValidationService(repository.Object, settings);

            // act
            var exception = await TestUtilities.ThrowsAsync <ValidationException>(async() => await validationService.ValidateOldPasswordAsync(obj.username, "something else"));

            // assert
            Assert.Equal(ValidationReason.PasswordIsIncorrect, exception.Reason);
            repository.Verify(x => x.AsQueryable <User>(), Times.Once);
        }
Exemple #5
0
        public void ChangePassword(SecureString newPassword)
        {
            if (null == newPassword || newPassword.Length <= 0)
            {
                throw new ArgumentException("Password must be provided.");
            }

            if (null == EncryptionInfo.ProtectedKey)
            {
                throw new ArgumentNullException("ProtectedKey");
            }

            try
            {
                using (var cu = new CryptoUtilities(EncryptionInfo.SelectedAlgorithm))
                {
                    // Re-encrypt encryption key with new password
                    EncryptionInfo.EncryptionKey = cu.ProtectEncryptionKey(newPassword,
                                                                           cu.UnprotectEncryptionKey(EncryptionInfo.ProtectedKey,
                                                                                                     EncryptionInfo.EncryptionKey, EncryptionInfo.IV),
                                                                           EncryptionInfo.Salt, EncryptionInfo.IV);

                    // Update protected key
                    SetupProtectedKey(newPassword);

                    // Update validation key
                    EncryptionInfo.ValidationKey = CryptoUtilities.GetValidationKey(newPassword, EncryptionInfo.Salt);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void TestValidCase()
        {
            // arrange
            var obj = new {
                username = "******",
                password = "******"
            };

            var repository = new Mock <IRepository>();
            var settings   = new ApplicationSettings();

            var set = TestUtilities.CreateDbSetMock(new List <User> {
                new User {
                    Username = obj.username, Password = CryptoUtilities.CreateHash(obj.password)
                },
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(set.Object);

            var validationService = new ValidationService(repository.Object, settings);

            // act
            Assert.DoesNotThrow(async() => await validationService.ValidateOldPasswordAsync(obj.username, obj.password));

            // assert
            repository.Verify(x => x.AsQueryable <User>(), Times.Exactly(1));
        }
    IEnumerator DeletePreviousError()
    {
        string name  = PlayerPrefs.GetString("error_on_delete_name");
        int    score = PlayerPrefs.GetInt("error_on_delete_score_A", 0);
        //int score_B = PlayerPrefs.GetInt("error_on_delete_score_B", 0);

        WWWForm form = new WWWForm();

        form.AddField("playerName", name);
        form.AddField("score_A", score);
        form.AddField("game", WWWConfig.gameName);
        string stringHashed = CryptoUtilities.MD5Sum(WWWConfig.gameName + name + score.ToString() + WWWConfig.hashKey);

        form.AddField("hash", stringHashed);
        WWW answer = new WWW(WWWConfig.setHighscoresInactivesURL, form);


        // Wait until the download is done
        yield return(answer);

        if (!string.IsNullOrEmpty(answer.error))
        {
            Debug.Log("Error downloading: " + answer.error);;
        }
        else
        {
            Debug.Log(answer.text);
            PlayerPrefs.DeleteKey("error_on_delete_score_A");
            PlayerPrefs.DeleteKey("error_on_delete_score_B");
            PlayerPrefs.DeleteKey("error_on_delete_name");
        }
    }
        public static string GetDiaryText(byte[] cipherText)
        {
            byte[] keyMaterial = Convert.FromBase64String(kmKey);

            return(CryptoUtilities.ByteArrayToString(
                       CryptoUtilities.Decrypt(cipherText, keyMaterial)));
        }
        public bool LoginToAccount(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            AccountStore store   = AccountStore.Create();
            Account      account = GetAccountFromStore(store, username);

            if (account == null)
            {
                return(false);
            }

            byte[] salt, hashedPassword;

            // Upgrade existing passwords to our new format
            if (!account.Properties.ContainsKey(key_salt))
            {
                salt           = CryptoUtilities.Get256BitSalt();
                hashedPassword = CryptoUtilities.GetHash(CryptoUtilities.StringToByteArray(account.Properties[key_password]), salt);
                account.Properties[key_password] = Convert.ToBase64String(hashedPassword);
                account.Properties.Add(key_salt, Convert.ToBase64String(salt));
                store.Save(account, service_id);
            }

            salt           = Convert.FromBase64String(account.Properties[key_salt]);
            hashedPassword = CryptoUtilities.GetHash(CryptoUtilities.StringToByteArray(password), salt);

            return(account.Properties[key_password] == Convert.ToBase64String(hashedPassword));
        }
Exemple #10
0
        internal static string GenerateHash(string value, string salt)
        {
            // Hash.
            string hash = CryptoUtilities.SHA256HashString(value + salt);

            // Return upper case.
            return(hash.ToUpper());
        }
        public virtual async Task ChangePasswordAsync(dynamic model)
        {
            _validationService.Bundles.ValidateNewPassword(model);

            var user = await _repository.UserByUsernameAsync((string)model.username);

            user.Password = CryptoUtilities.CreateHash((string)model.password);

            await _repository.UpdateAsync(user);
        }
        public void TestInvalidPassword()
        {
            // arrange
            var hash = CryptoUtilities.CreateHash("password");

            // act
            var valid = CryptoUtilities.ValidatePassword("something else", hash);

            // assert
            Assert.False(valid);
        }
Exemple #13
0
        public virtual async Task ValidateOldPasswordAsync(string username, string oldPassword)
        {
            var user = await _repository.UserByUsernameAsync(username);

            var valid = user != null && CryptoUtilities.ValidatePassword(oldPassword, user.Password);

            if (!valid)
            {
                throw new ValidationException(ValidationReason.PasswordIsIncorrect);
            }
        }
Exemple #14
0
        public virtual async Task ResetPasswordAsync(dynamic model)
        {
            _validationService.Bundles.ValidateNewPassword(model);

            string q = model.q;

            int    id;
            string ciphertext;

            try {
                var split = q.Split(new[] { ':' });

                id         = int.Parse(split[0]);
                ciphertext = split[1];
            }
            catch {
                throw new ServiceException(ServiceReason.InvalidUserRequest);
            }

            var request = await _repository.GetAsync <UserRequest>(id);

            if (request == null || request.RequestType != UserRequestType.ResetPassword)
            {
                throw new ServiceException(ServiceReason.InvalidUserRequest);
            }

            try {
                var plaintext = CryptoUtilities.Decrypt(ciphertext, request.Key, request.IV);

                dynamic obj = JObject.Parse(plaintext);

                var credentials = new User {
                    Username = obj.username,
                    Password = obj.password
                };

                if (!CryptoUtilities.ValidatePassword(credentials.Password, request.Password))
                {
                    throw new ServiceException(ServiceReason.ResetPasswordError);
                }

                var user = await _repository.UserByUsernameAsync(credentials.Username);

                user.Password = CryptoUtilities.CreateHash((string)model.password);

                await _repository.UpdateAsync(user);

                await _repository.UpdateAsync(request);
            }
            catch {
                throw new ServiceException(ServiceReason.ResetPasswordError);
            }
        }
        public async Task TestWithInvalidUserRequestAsync()
        {
            // arrange
            var obj = new {
                username = "******",
                password = "******"
            };

            var repository            = new Mock <IRepository>();
            var settings              = new ApplicationSettings();
            var validationService     = new Mock <ValidationService>(repository.Object, settings);
            var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object);
            var mailService           = new Mock <MailService>(repository.Object);

            validationService
            .SetupGet(x => x.Bundles)
            .Returns(new ValidationBundles(validationService.Object));

            var request = new UserRequest {
                Id          = 1,
                Username    = obj.username,
                RequestType = UserRequestType.Activation
            };

            repository
            .Setup(x => x.GetAsync <UserRequest>(1))
            .ReturnsAsync(request);

            var credentials = JObject.FromObject(obj);

            string q;

            using (var algorithm = TripleDES.Create()) {
                var ciphertext = CryptoUtilities.Encrypt(credentials.ToString(), algorithm.Key, algorithm.IV);

                q = 1 + ":" + ciphertext;
            }

            dynamic model = JObject.FromObject(new {
                q
            });

            var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object);

            // act
            var exception = await TestUtilities.ThrowsAsync <ServiceException>(async() => await accountService.ResetPasswordAsync(model));

            // assert
            Assert.Equal(ServiceReason.InvalidUserRequest, exception.Reason);

            repository.Verify(x => x.GetAsync <UserRequest>(It.IsAny <int>()), Times.Once);
        }
        // Decryption of goal description - coming from SQLite database
        string GetGoalText(byte[] cipherText)
        {
            Account account = accountManager.CheckForAccount();

            if (!account.Properties.TryGetValue("keymaterial", out string keyString))
            {
                return(String.Empty);
            }

            byte[] keyMaterial = Convert.FromBase64String(keyString);

            return(CryptoUtilities.ByteArrayToString(CryptoUtilities.Decrypt(cipherText, keyMaterial)));
        }
        // Encryption of goal description
        byte[] GetCipherText(string diaryText)
        {
            Account account = accountManager.CheckForAccount();

            if (!account.Properties.TryGetValue("keymaterial", out string keyString))
            {
                return(null);
            }

            byte[] keyMaterial = Convert.FromBase64String(keyString);

            return(CryptoUtilities.Encrypt(CryptoUtilities.StringToByteArray(diaryText), keyMaterial));
        }
        string GetDiaryText(byte[] cipherText)
        {
            string keyString;

            if (!account.Properties.TryGetValue(kmKey, out keyString))
            {
                return(string.Empty);
            }

            byte[] keyMaterial = Convert.FromBase64String(keyString);

            return(CryptoUtilities.ByteArrayToString(CryptoUtilities.Decrypt(cipherText, keyMaterial)));
        }
        byte[] GetCipherText(string diaryText)
        {
            string keyString;

            if (!account.Properties.TryGetValue(kmKey, out keyString))
            {
                return(null);
            }

            byte[] keyMaterial = Convert.FromBase64String(keyString);

            return(CryptoUtilities.Encrypt(CryptoUtilities.StringToByteArray(diaryText), keyMaterial));
        }
        public void TestDefaultBehavior()
        {
            // arrange/act
            var hash = CryptoUtilities.CreateHash("password");

            // assert
            var tokens = hash.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

            Assert.Equal(3, tokens.Length);
            Assert.Equal(Constants.Cryptography.HASH_ITERATIONS, int.Parse(tokens[0]));
            Assert.Equal(Constants.Cryptography.SALT_BYTE_SIZE, Convert.FromBase64String(tokens[1]).Length);
            Assert.Equal(Constants.Cryptography.HASH_BYTE_SIZE, Convert.FromBase64String(tokens[2]).Length);
        }
Exemple #21
0
        public void GenerateKey()
        {
            var a = CryptoUtilities.GenerateKey(32);
            //Debug.WriteLine("UTF8 - " + new String(Encoding.UTF8.GetChars(a)));
            //Debug.WriteLine("unicode [little Endian] - " + Encoding.Unicode.GetChars(a));
            //Debug.WriteLine("unicode [big endian]- " + Encoding.BigEndianUnicode.GetChars(a));
            //Debug.WriteLine("ASCI - " + Encoding.ASCII.GetChars(a));
            string b64 = Convert.ToBase64String(a);

            Debug.WriteLine("Base64 - " + b64);
            CollectionAssert.AreEqual(a, Convert.FromBase64String(b64));
            Debug.WriteLine("Byte[] - new byte[] {" + string.Join(",", a) + '}');
        }
Exemple #22
0
        public virtual async Task SignInAsync(HttpContextBase httpContext, dynamic model)
        {
            var user = await _repository.UserByEmailAsync((string)model.email);

            if (user == null || !user.Enabled || !CryptoUtilities.ValidatePassword((string)model.password, user.Password))
            {
                throw new ServiceException(ServiceReason.InvalidCredentials);
            }

            bool rememberMe = model.rememberMe ?? false;

            CreateAuthorizationTicket(httpContext, user, rememberMe);
        }
        public async Task TestWithInvalidPasswordAsync()
        {
            // arrange
            var obj = new {
                email      = "*****@*****.**",
                password   = "******",
                rememberMe = false
            };

            var repository            = new Mock <IRepository>();
            var settings              = new ApplicationSettings();
            var validationService     = new Mock <ValidationService>(repository.Object, settings);
            var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object);
            var mailService           = new Mock <MailService>(repository.Object);
            var httpContext           = new Mock <HttpContextBase>();
            var httpResponse          = new Mock <HttpResponseBase>();
            var cookies = new HttpCookieCollection();

            var user = new User {
                Email    = obj.email,
                Password = CryptoUtilities.CreateHash("something else")
            };

            var userSet = TestUtilities.CreateDbSetMock(new List <User> {
                user
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(userSet.Object);

            httpContext
            .SetupGet(x => x.Response)
            .Returns(httpResponse.Object);

            httpResponse
            .SetupGet(x => x.Cookies)
            .Returns(cookies);

            dynamic model = JObject.FromObject(obj);

            var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object);

            // act
            var exception = await TestUtilities.ThrowsAsync <ServiceException>(async() => await accountService.SignInAsync(httpContext.Object, model));

            // assert
            Assert.Equal(exception.Reason, ServiceReason.InvalidCredentials);

            httpResponse.VerifyGet(x => x.Cookies, Times.Never);
        }
        public async Task TestDefaultBehaviorAsync()
        {
            // arrange
            var obj = new {
                email      = "*****@*****.**",
                password   = "******",
                rememberMe = false
            };

            var repository            = new Mock <IRepository>();
            var settings              = new ApplicationSettings();
            var validationService     = new Mock <ValidationService>(repository.Object, settings);
            var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object);
            var mailService           = new Mock <MailService>(repository.Object);
            var httpContext           = new Mock <HttpContextBase>();
            var httpResponse          = new Mock <HttpResponseBase>();
            var cookies = new HttpCookieCollection();

            var user = new User {
                Email    = obj.email,
                Password = CryptoUtilities.CreateHash(obj.password),
                Enabled  = true
            };

            var userSet = TestUtilities.CreateDbSetMock(new List <User> {
                user
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(userSet.Object);

            httpContext
            .SetupGet(x => x.Response)
            .Returns(httpResponse.Object);

            httpResponse
            .SetupGet(x => x.Cookies)
            .Returns(cookies);

            dynamic model = JObject.FromObject(obj);

            var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object);

            // act
            await TestUtilities.DoesNotThrowAsync(async() => await accountService.SignInAsync(httpContext.Object, model));

            // assert
            Assert.Equal(httpResponse.Object.Cookies[".ASPXAUTH"].Expires, DateTime.MinValue);
        }
        public void TestValidPassword()
        {
            // arrange
            var obj = new {
                password = "******"
            };

            var hash = CryptoUtilities.CreateHash(obj.password);

            // act
            var valid = CryptoUtilities.ValidatePassword(obj.password, hash);

            // assert
            Assert.True(valid);
        }
        private static User SeedUser(DbContext context, string firstName, string lastName, string username, string email, string password)
        {
            var entity = new User {
                FirstName   = firstName,
                LastName    = lastName,
                Username    = username,
                Email       = email,
                Password    = CryptoUtilities.CreateHash(password),
                Enabled     = true,
                CreatedDate = DateTime.UtcNow
            };

            context.Set <User>().Add(entity);

            return(entity);
        }
        public async Task TestDefaultBehaviorAsync()
        {
            // arrange
            var obj = new {
                username        = "******",
                oldPassword     = "******",
                password        = "******",
                confirmPassword = "******"
            };

            var repository            = new Mock <IRepository>();
            var settings              = new ApplicationSettings();
            var validationService     = new Mock <ValidationService>(repository.Object, settings);
            var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object);
            var mailService           = new Mock <MailService>(repository.Object);

            var user = new User {
                Username = obj.username,
                Password = CryptoUtilities.CreateHash(obj.oldPassword)
            };

            var set = TestUtilities.CreateDbSetMock(new List <User> {
                user
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(set.Object);

            dynamic model = JObject.FromObject(new {
                obj.oldPassword,
                obj.password,
                obj.confirmPassword
            });

            var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object);

            // act
            await accountService.ChangePasswordAsync(obj.username, model);

            // assert
            Assert.Equal(obj.username, (string)model.username);

            validationService.Verify(x => x.ValidateOldPasswordAsync(obj.username, obj.oldPassword), Times.Once);

            administrationService.Verify(x => x.ChangePasswordAsync(It.IsAny <object>()), Times.Once);
        }
        public void TestDefaultBehavior()
        {
            // arrange
            var obj = new {
                plaintext = "secret"
            };

            string ciphertext;

            // act
            using (var algorithm = TripleDES.Create()) {
                ciphertext = CryptoUtilities.Encrypt(obj.plaintext, algorithm.Key, algorithm.IV);
            }

            // assert
            Assert.NotEqual(obj.plaintext, ciphertext);
        }
Exemple #29
0
    // Use this for initialization
    IEnumerator Upload()
    {
        if (PlayerPrefs.GetInt("active_mode", 1) == 2)
        {
            highscore_url = WWWConfig.highscoreURL_B;
            scoreToAskFor = "highscore_b";
        }

        playName = PlayerPrefs.GetString("name", "");
        score    = PlayerPrefs.GetInt(scoreToAskFor, 0);

        if ((playName != "") && (score != 0))
        {
            // Create a form object for sending high score data to the server
            WWWForm form = new WWWForm();
            // Assuming the perl script manages high scores for different games
            form.AddField("game", WWWConfig.gameName);
            // The name of the player submitting the scores
            form.AddField("playerName", playName);
            // The score
            form.AddField("score", score);
            // The hash
            string stringHashed = CryptoUtilities.MD5Sum(WWWConfig.gameName + playName + score.ToString() + WWWConfig.hashKey);
            form.AddField("hash", stringHashed);

            // Create a download object
            WWW download = new WWW(highscore_url, form);

            // Wait until the download is done
            yield return(download);

            if (!string.IsNullOrEmpty(download.error))
            {
                Debug.Log("Error downloading: " + download.error);
            }
            else
            {
                Debug.Log(download.text);
            }
        }
        else
        {
            Debug.Log("PlayerName vacío o Highscore = 0");
        }
    }
Exemple #30
0
        // TODO: Exception handling

        /// <summary>
        /// Fills <c>EncryptionInfo</c> structure and prepares vault
        /// for encryption.
        /// </summary>
        public void SetupEncryption(SecureString password)
        {
            if (null == password)
            {
                throw new ArgumentNullException("password");
            }

            EncryptionInfo.Salt          = CryptoUtilities.RandomBytes(16);
            EncryptionInfo.IV            = CryptoUtilities.RandomBytes(16);
            EncryptionInfo.ValidationKey = CryptoUtilities.GetValidationKey(password, EncryptionInfo.Salt);
            EncryptionInfo.ProtectedKey  = CryptoUtilities.GetEncryptionProtectionKey(password, EncryptionInfo.Salt);

            // Protecting encryption key using chosen encryption algorythm
            using (var cu = new CryptoUtilities(EncryptionInfo.SelectedAlgorithm))
            {
                EncryptionInfo.EncryptionKey = cu.ProtectEncryptionKey(password,
                                                                       CryptoUtilities.RandomBytes(16), EncryptionInfo.Salt, EncryptionInfo.IV);
            }
        }