Пример #1
0
        public SaltedBytesCache(
            SecureHead secureHead,
            SecurePassword securePassword)
        {
            if (secureHead == null)
            {
                throw new ArgumentException("secureHead should NOT be null.");
            }
            if (securePassword == null)
            {
                throw new ArgumentException("securePassword should NOT be null.");
            }
            byte[] saltedPasswordBytes = GetSaltedPassowrdBytes(secureHead, securePassword);
            if (BytesHelper.IsNullOrEmptyArray(saltedPasswordBytes) == true)
            {
                throw new ArgumentException("saltedPasswordBytes should NOT be null.");
            }
            byte[] saltedInitialVectorBytes = GetSaltedInitialVectorBytes(secureHead);
            if (BytesHelper.IsNullOrEmptyArray(saltedInitialVectorBytes) == true)
            {
                throw new ArgumentException("saltedInitialVectorBytes should NOT be null.");
            }

            SecureHead              = secureHead;
            SaltedPasswordBytes     = saltedPasswordBytes;
            SaltedInitiaVectorBytes = saltedInitialVectorBytes;
        }
Пример #2
0
        public bool CheckPassword(LoginRequestDTO request)
        {
            using (var con = new SqlConnection(builder.ConnectionString))
                using (var com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();

                    // Sprawdzanie haseł sprzed ich zabezpieczenia
                    //   com.CommandText = "SELECT 1 FROM Student WHERE IndexNumber=@number AND Password=@Password";
                    //   com.Parameters.AddWithValue("number", request.Login);
                    //  com.Parameters.AddWithValue("Password", request.Password);

                    //    var dr = com.ExecuteReader();

                    //   return dr.Read();

                    com.CommandText = "SELECT Password,Salt FROM Student WHERE IndexNumber=@number";
                    com.Parameters.AddWithValue("number", request.Login);

                    using var dr = com.ExecuteReader();

                    if (dr.Read())
                    {
                        return(SecurePassword.Validate(request.Password, dr["Salt"].ToString(), dr["Password"].ToString()));
                    }
                    return(false); //Nie ma nawet takiego indeksu w bazie danych
                }
        }
Пример #3
0
        /// <summary>
        /// Method to add new text into SecureString and process visual output.
        /// </summary>
        private void AddToSecureString(string text)
        {
            if (PwdContainer.SelectionLength > 0)
            {
                RemoveFromSecureString(PwdContainer.SelectionStart, PwdContainer.SelectionLength);
            }

            foreach (char c in text)
            {
                int caretIndex = PwdContainer.CaretIndex;
                SecurePassword.InsertAt(caretIndex, c);
                MaskAllDisplayText();
                if (caretIndex == PwdContainer.Text.Length)
                {
                    _maskTimer.Stop();
                    _maskTimer.Start();
                    PwdContainer.Text = PwdContainer.Text.Insert(caretIndex++, c.ToString());
                }
                else
                {
                    PwdContainer.Text = PwdContainer.Text.Insert(caretIndex++, "●");
                }
                PwdContainer.CaretIndex = caretIndex;
            }
        }
Пример #4
0
        protected override void HandleBackspace(bool isCtrlDown)
        {
            if (HasFocus && caretIndex > 0)
            {
                if (isCtrlDown)
                {
                    for (int i = caretIndex - 1; i > -1; i--)
                    {
#if UWP
                        password = password.Remove(i);
#else
                        SecurePassword.RemoveAt(i);
#endif
                    }

                    caretIndex = 0;
                }
                else
                {
                    var whereToRemoveFrom = caretIndex - 1;
                    // Move the care to the left one before removing from the text. Otherwise, if the
                    // caret is at the end of the word, modifying the word will shift the caret to the left,
                    // and that could cause it to shift over two times.
                    caretIndex--;
#if UWP
                    password = password.Remove(whereToRemoveFrom);
#else
                    SecurePassword.RemoveAt(whereToRemoveFrom);
#endif
                }
                UpdateDisplayedCharacters();
                PasswordChanged?.Invoke(this, null);
            }
        }
Пример #5
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         SecurePassword?.Dispose();
     }
 }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //hash the password
            var hashedPassword = Convert.ToBase64String(SecurePassword.HashPassword(model.Email, model.Password));

            //modify the model
            model.Password        = hashedPassword;
            model.ConfirmPassword = hashedPassword;

            var user = new ApplicationUser()
            {
                UserName = model.Email, Email = model.Email
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Пример #7
0
        private void button_Click(object sender, EventArgs e)
        {
            if (sender.Equals(this.buttonUpdate))
            {
                if (this.textexApplicationRoleName.Text.Trim() != "" && this.textexApplicationRolePassword.Text.Trim() != "")
                {
                    IBaseRepository baseRepository = CommonNinject.Kernel.Get <IBaseRepository>();
                    if (baseRepository.UpdateApplicationRole(SecurePassword.Encrypt(this.textexApplicationRoleName.Text.Trim()), SecurePassword.Encrypt(this.textexApplicationRolePassword.Text.Trim())) == 1)
                    {
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        throw new Exception("Fail to update application role.");
                    }
                }
            }
            else
            if (sender.Equals(this.buttonApplicationRoleRequired) || sender.Equals(this.buttonApplicationRoleIgnored))
            {
                CommonConfigs.AddUpdateAppSetting("ApplicationRoleRequired", sender.Equals(this.buttonApplicationRoleRequired) ? "true" : "false");

                CustomMsgBox.Show(this, "Please open your program again in order to take new effect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                this.DialogResult = DialogResult.Cancel;
            }
            else
            {
                this.DialogResult = DialogResult.Cancel;
            }
        }
        protected virtual bool CanLoginExecute()
        {
            string password = null;

            if (SecurePassword != null && SecurePassword.Length > 0)
            {
                password = SecurePassword.ConvertToUnsecureString();
            }
            if (!String.IsNullOrWhiteSpace(Password))
            {
                password = Password;
            }

            bool isUsernameValid           = !String.IsNullOrWhiteSpace(Username);
            bool isPasswordValid           = !String.IsNullOrWhiteSpace(password);
            bool isAuthenticationCodeValid = !String.IsNullOrWhiteSpace(AuthenticationCode);

            if (IsAuthenticationCodeRequired)
            {
                return(isAuthenticationCodeValid);
            }
            else
            {
                return(isUsernameValid & isPasswordValid);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            var hashedPassword = Convert.ToBase64String(SecurePassword.HashPassword(context.UserName, context.Password));

            ApplicationUser user = await userManager.FindAsync(context.UserName, hashedPassword);

            if (user == null)
            {
                context.SetError("invalid_grant", "The username or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Пример #10
0
        public async Task <ActionResult <VendorUserForGetDTO> > Post(VendorUserForAddDTO model)
        {
            if (await _vendorUserRepository.IsExistByPhone(model.Phone).ConfigureAwait(true))
            {
                return(Conflict(new ApiResponse(409, StringConcatenates.Exist("Phone", model.Phone))));
            }

            if (await _vendorUserRepository.IsExistByEmail(model.Email).ConfigureAwait(true))
            {
                return(Conflict(new ApiResponse(409, StringConcatenates.Exist("Email", model.Email))));
            }

            VendorUser vendorUser = _mapper.Map <VendorUser>(model);
            string     password   = SecurePassword.GeneratePassword(8);

            SecurePassword.CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);
            vendorUser.PasswordHash = passwordHash;
            vendorUser.PasswordSalt = passwordSalt;

            await _vendorUserRepository.AddAsync(vendorUser).ConfigureAwait(true);

            await _unitOfWork.CompleteAsync().ConfigureAwait(true);

            Email.Send("Momen", vendorUser.Email, "password", password);

            VendorUserForGetDTO vendorUserDto = _mapper.Map <VendorUserForGetDTO>(vendorUser);

            return(Ok(vendorUserDto));
        }
Пример #11
0
        private void buttonChange_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.textBoxCurrentPassword.Visible)
                {
                    this.textBoxCurrentPassword.Visible = false;
                    this.textBoxNewPassword.Visible     = true;
                    this.textBoxConfirmPassword.Visible = true;
                    this.labelCurrentPassword.Visible   = false;
                    this.labelNewPassword.Visible       = true;
                    this.labelConfirmPassword.Visible   = true;
                    this.SetButtonEnabled();
                    this.DialogResult = DialogResult.None;
                }
                else
                {
                    string passwordHash = this.textBoxNewPassword.Text;
                    if (passwordHash != "")
                    {
                        passwordHash = SecurePassword.Encrypt(passwordHash);
                    }

                    UserAPIs userAPIs = new UserAPIs(CommonNinject.Kernel.Get <IUserAPIRepository>());
                    if (userAPIs.SetPasswordHash(ContextAttributes.User.UserID, passwordHash) == 1)
                    {
                        this.DialogResult = DialogResult.Yes;
                    }
                }
            }
            catch (Exception exception)
            {
                ExceptionHandlers.ShowExceptionMessageBox(this, exception);
            }
        }
Пример #12
0
        private void Login_Click(object sender, RoutedEventArgs e)
        {
            bool           rememberMe = cbxRememberMe.IsChecked.HasValue ? cbxRememberMe.IsChecked.Value : false;
            SecurePassword password   = new SecurePassword(txtPassword.SecurePassword);

            Login(rememberMe, password);
        }
        public ISecureCrypto CreateCrypto(SecurePassword password)
        {
            ISecureCrypto crypto = new SecureCrypto();

            crypto.Config.Password = password;

            return(crypto);
        }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         EventAggregator.Unsubscribe(this);
         SecurePassword?.Dispose();
     }
 }
Пример #15
0
        public void ExecuteCreateUser(object o)
        {
            string newUserPassword        = null;
            string newUserConfirmPassword = null;

            if (SecurePassword != null & SecureConfirmPassword != null)
            {
                newUserPassword        = SecurePassword.GetString();
                newUserConfirmPassword = SecureConfirmPassword.GetString();
            }

            // Checks to see if input fields are empty or null
            if (String.IsNullOrEmpty(Username) || String.IsNullOrEmpty(newUserPassword) || String.IsNullOrEmpty(newUserConfirmPassword))
            {
                CredentialStatus = "Please input all fields";
                return;
            }

            // Check if user already exists in database
            if (SQLiteDataAccess.DoesUserExist(Username))
            {
                CredentialStatus = "User already exists";
                return;
            }

            // Checks to see if both passwords match before creating a new user
            if (newUserPassword == newUserConfirmPassword)
            {
                byte[] masterKey = CryptoUtil.GenerateByteArray(32);
                byte[] salt      = CryptoUtil.GenerateByteArray(32);

                // Creates the Key Encryption Key derived from the master password using PBKDF2-SHA256
                byte[] keyEncryptionKey = CryptoUtil.ComputePBKDF2Hash(newUserPassword, salt);

                // Encrypts the master key using the Key Encryption Key and converts it to a base64 string for storage
                string encryptedMasterKey = Convert.ToBase64String(CryptoUtil.AES_GCMEncrypt(masterKey, keyEncryptionKey));

                Console.WriteLine($"{Username} - Master Key: {Convert.ToBase64String(masterKey)}");
                Console.WriteLine($"{Username} - Key Encryption Key: {Convert.ToBase64String(keyEncryptionKey)}");
                Console.WriteLine($"{Username} - Encrypted Master Key: {encryptedMasterKey}");

                UserModel newUser = new UserModel
                {
                    Username = Username,
                    Password = encryptedMasterKey,
                    Salt     = Convert.ToBase64String(salt)
                };

                SQLiteDataAccess.CreateUser(newUser);

                var parentConductor = this.Parent as Conductor <Screen>;
                parentConductor.ActivateItem(new LoginViewModel());
            }
            else
            {
                CredentialStatus = "Passwords do not match";
            }
        }
Пример #16
0
 private void Dispose(bool disposing)
 {
     if (!_disposed && disposing)
     {
         SecurePassword.Clear();
         SecurePassword.Dispose();
     }
     _disposed = true;
 }
        public static void CreateIdentity(MvcIdentityModel identity)
        {
            var computed = MvcIdentityModel.New(identity);

            computed.Password  = SecurePassword.Hash(computed.Password);
            computed.Password2 = computed.Password;
            computed.Status    = "active";
            Database.Insert("identities", computed.ToDbModel());
        }
Пример #18
0
        public override bool Execute()
        {
            SecurePassword sp;
            TimeSpan       it10000 = Execute(10000, out sp);

            byte[] result = new byte[]
            { // "MyPassword" hashed 10000 times with SHA-256
                205, 145, 243, 77, 50, 200, 192, 188, 86, 174,
                137, 126, 223, 26, 124, 17, 175, 42, 231, 102,
                86, 106, 249, 206, 3, 115, 220, 114, 251, 203,
                107, 112, 192, 168, 46, 122, 163, 219, 30, 211,
                83, 254, 146, 140, 205, 36, 35, 235, 229, 249,
                170, 193, 117, 76, 250, 133, 144, 96, 225, 241,
                250, 43, 33, 170
            };

            if (result.Length != sp.Bytes.Length)
            {
                return(false);
            }

            if (!sp.Bytes.All((b, i) => result[i] == b))
            {
                return(false);
            }

            // Without auto-clean
            sp = new SecurePassword(
                password: ProvideSecureString(),
                nbHash: 10000,
                autoClear: false
                );

            if (result.Length != sp.Bytes.Length)
            {
                return(false);
            }

            if (!sp.Bytes.All((b, i) => result[i] == b))
            {
                return(false);
            }

            if (IsVerbose)
            {
                WriteLine("   10 000 iterations : " + it10000);

                TimeSpan it100000 = Execute(100000, out sp);
                WriteLine("  100 000 iterations : " + it100000);

                TimeSpan it1000000 = Execute(1000000, out sp);
                WriteLine("1 000 000 iterations : " + it1000000);
            }

            return(true);
        }
Пример #19
0
        public void Clear()
        {
#if UWP
            password = null;
#else
            SecurePassword.Clear();
#endif
            UpdateDisplayedCharacters();
            PasswordChanged?.Invoke(this, null);
        }
Пример #20
0
        private User AuthenticateUser(UserDTO login)
        {
            User user = _context.Users.SingleOrDefault(x => x.UserName == login.UserName);

            if (SecurePassword.ConfirmPassword(login.Password, user.Password))
            {
                return(user);
            }
            return(null);
        }
Пример #21
0
        private Dictionary <string, string> BuildCredentialDetails(string passwordFieldName = "Password")
        {
            var fields = SelectedCompany.CredentialFields.ToDictionary(field => field.Name, field => field.Value);

            if (fields.ContainsKey(passwordFieldName))
            {
                fields[passwordFieldName] = SecurePassword?.ConvertToUnsecureString() ?? string.Empty;
            }
            return(fields);
        }
Пример #22
0
 public Password(Password pwd)
 {
     Id             = pwd.Id;
     Name           = pwd.Name;
     Login          = pwd.Login;
     Url            = pwd.Url;
     Description    = pwd.Description;
     SecurePassword = pwd.SecurePassword;
     SecurePassword.MakeReadOnly();
 }
Пример #23
0
 public Customer(string username, string password, string firstName, string lastName, UserEnum userType)
 {
     Username       = username;
     PasswordSalt   = Utilities.CreateSalt();
     SecurePassword = new SecurePassword(password, PasswordSalt);
     PasswordHash   = SecurePassword.ComputeSaltedHash();
     FirstName      = firstName;
     LastName       = lastName;
     UserType       = userType;
     ID             = Guid.NewGuid();
 }
Пример #24
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (SecurePassword != null)
         {
             SecurePassword.Dispose();
             SecurePassword = null;
         }
     }
 }
Пример #25
0
        internal override void ApplyTo(DictionaryRequestParameters requestParameters)
        {
            requestParameters[OAuthParameter.GrantType] = OAuthGrantType.Password;
            requestParameters[OAuthParameter.Username]  = this.UserName;
            requestParameters[OAuthParameter.Password]  = new string(PasswordToCharArray());

            if (SecurePassword != null)
            {
                SecurePassword.Clear();
            }
        }
        public async Task <IActionResult> ChangePassword(UserForChangePasswordDTO model)
        {
            User user = await userRepository.Get(model.Id).ConfigureAwait(true);

            SecurePassword.CreatePasswordHash(model.Password, out byte[] passwordHash, out byte[] passwordSalt);
            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;
            userRepository.Edit(user);
            await unitOfWork.CompleteAsync().ConfigureAwait(true);

            return(Ok(mapper.Map <UserForGetDTO>(await userRepository.Get(user.Id).ConfigureAwait(true))));
        }
Пример #27
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
#if !PCL
                if (SecurePassword != null)
                {
                    SecurePassword.Dispose();
                }
#endif
            }
        }
Пример #28
0
 /// <summary>
 ///     Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing">
 ///     <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
 ///     unmanaged resources.
 /// </param>
 private void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             SecurePassword.Clear();
             SecurePassword.Dispose();
         }
     }
     disposed = true;
 }
Пример #29
0
        /// <summary>
        /// Method to remove text from SecureString and process visual output.
        /// </summary>
        private void RemoveFromSecureString(int startIndex, int trimLength)
        {
            int caretIndex = PwdContainer.CaretIndex;

            for (int i = 0; i < trimLength; ++i)
            {
                SecurePassword.RemoveAt(startIndex);
            }

            PwdContainer.Text       = PwdContainer.Text.Remove(startIndex, trimLength);
            PwdContainer.CaretIndex = caretIndex;
        }
Пример #30
0
 void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (disposed)
         {
             return;
         }
         SecurePassword.Clear();
         SecurePassword.Dispose();
         disposed = true;
     }
 }
Пример #31
0
        private async void SecurePasswordTester()
        {
            SecurePassword<Credential> pass = new SecurePassword<Credential>();
            await pass.Load();

            Credential credential = new Credential();

            credential.Username = "******";
            credential.Password = "******";
            credential.Token = "42";

            Wygwam.Windows.Phone.Info.DeviceInfo info = Wygwam.Windows.Phone.Info.DeviceInfo.Current;
            Debug.WriteLine("name =>" + info.Name);
            Debug.WriteLine("OS =>" + info.OS);
            Debug.WriteLine("OSVersion =>" + info.OSVersion);

            pass.Add(credential);
        }