Exemplo n.º 1
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);
            }
        }
        public void TestInvalidPassword()
        {
            // arrange
            var hash = CryptoUtilities.CreateHash("password");

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

            // assert
            Assert.False(valid);
        }
Exemplo n.º 3
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);
            }
        }
Exemplo n.º 4
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 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);
        }
Exemplo n.º 6
0
        public void DecryptFromFile(string filePath, SecureString password)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentNullException("File path is empty.");
            }

            try
            {
                // Reading vault from file

                //string xml = string.Empty;

                //using (FileStream sourceStream = new FileStream(filePath,
                //    FileMode.Open, FileAccess.Read, FileShare.Read,
                //    bufferSize: 4096, useAsync: true))
                //{
                //    StringBuilder sb = new StringBuilder();

                //    byte[] buffer = new byte[0x1000];
                //    int numRead;
                //    while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                //    {
                //        string text = Encoding.UTF8.GetString(buffer, 0, numRead);
                //        sb.Append(text);
                //    }

                //    xml = sb.ToString();
                //}

                // Deserializing vault

                var xml = File.ReadAllText(filePath);

                XmlSerializer serializer = new XmlSerializer(typeof(Vault));
                using (TextReader reader = new StringReader(xml))
                {
                    var vault = (Vault)serializer.Deserialize(reader);
                    EncryptionInfo = vault.EncryptionInfo;
                    Data           = vault.Data;
                    Name           = vault.Name;
                    Description    = vault.Description;
                }

                using (var cu = new CryptoUtilities(EncryptionInfo.SelectedAlgorithm))
                {
                    if (!CryptoUtilities.ValidatePassword(password, EncryptionInfo.ValidationKey, EncryptionInfo.Salt))
                    {
                        throw new ArgumentException("Incorrect password.");
                    }

                    // Unprotect the key and decrypt data

                    var plainData = cu.Decrypt(Data, cu.UnprotectEncryptionKey(password,
                                                                               EncryptionInfo.EncryptionKey, EncryptionInfo.Salt, EncryptionInfo.IV),
                                               EncryptionInfo.IV);

                    // Deserialize folder list

                    serializer = new XmlSerializer(typeof(MvxObservableCollection <Folder>));
                    using (TextReader reader = new StringReader(Encoding.UTF8.GetString(plainData)))
                    {
                        FolderList = (MvxObservableCollection <Folder>)serializer.Deserialize(reader);
                    }

                    // Set vault's Location
                    Location = filePath;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 7
0
        public void EncryptToFile(string filepath, SecureString password)
        {
            #region Parameter Checks

            if (null == filepath)
            {
                throw new ArgumentNullException("Filepath can't be empty");
            }

            if (null == EncryptionInfo)
            {
                throw new NullReferenceException("EncryptionInfo can't be empty");
            }

            if (null == EncryptionInfo.EncryptionKey)
            {
                throw new NullReferenceException("EncryptionKey can't be empty");
            }

            if (null == EncryptionInfo.ValidationKey)
            {
                throw new NullReferenceException("ValidationKey can't be empty");
            }

            if (null == EncryptionInfo.IV)
            {
                throw new NullReferenceException("IV can't be empty");
            }

            if (null == EncryptionInfo.Salt)
            {
                throw new NullReferenceException("Salt can't be empty");
            }

            #endregion Parameter Checks

            try
            {
                using (var cu = new CryptoUtilities(EncryptionInfo.SelectedAlgorithm))
                {
                    if (!CryptoUtilities.ValidatePassword(password, EncryptionInfo.ValidationKey, EncryptionInfo.Salt))
                    {
                        throw new ArgumentException("Incorrect password");
                    }

                    // Serialize and encrypt folder list

                    XmlSerializer xsSubmit = new XmlSerializer(typeof(MvxObservableCollection <Folder>));
                    var           xml      = string.Empty;

                    using (var sww = new StringWriter())
                        using (XmlWriter writer = XmlWriter.Create(sww))
                        {
                            xsSubmit.Serialize(writer, FolderList);
                            xml = sww.ToString(); // Serialized XML
                        }

                    // Unprotect the key and encrypt data

                    Data = cu.Encrypt(Encoding.UTF8.GetBytes(xml),
                                      cu.UnprotectEncryptionKey(password,
                                                                EncryptionInfo.EncryptionKey, EncryptionInfo.Salt, EncryptionInfo.IV),
                                      EncryptionInfo.IV);

                    // Serialize vault and save to file

                    xsSubmit = new XmlSerializer(typeof(Vault));
                    xml      = string.Empty;

                    using (var sww = new StringWriter())
                        using (XmlWriter writer = XmlWriter.Create(sww))
                        {
                            xsSubmit.Serialize(writer, GetInstance());
                            xml = sww.ToString(); // Serialized XML
                        }

                    File.WriteAllText(filepath, xml);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 8
0
        public async Task TestDefaultBehaviorAsync()
        {
            // arrange
            var obj = new {
                username = "******",
                password = "******"
            };

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

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

            var user = new User {
                Username = obj.username
            };

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

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

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

            repository
            .Setup(x => x.GetAsync <User>(1))
            .ReturnsAsync(user);

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

            var password    = Guid.NewGuid().ToString();
            var credentials = JObject.FromObject(new {
                obj.username,
                password
            });

            string q;

            using (var algorithm = TripleDES.Create()) {
                request.Key      = algorithm.Key;
                request.IV       = algorithm.IV;
                request.Password = CryptoUtilities.CreateHash(password);

                var ciphertext = CryptoUtilities.Encrypt(credentials.ToString(), algorithm.Key, algorithm.IV);

                q = 1 + ":" + ciphertext;
            }

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

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

            // act
            await TestUtilities.DoesNotThrowAsync(async() => await accountService.ResetPasswordAsync(model));

            // assert
            Assert.True(CryptoUtilities.ValidatePassword(obj.password, user.Password));

            validationBundles.Verify(x => x.ValidateNewPassword(It.IsAny <object>()), Times.Once);

            repository.Verify(x => x.GetAsync <UserRequest>(It.IsAny <int>()), Times.Once);
            repository.Verify(x => x.AsQueryable <User>(), Times.Once);
            repository.Verify(x => x.UpdateAsync(user), Times.Once());
            repository.Verify(x => x.UpdateAsync(request), Times.Once());
        }