コード例 #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();
     }
 }
コード例 #6
0
        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;
            }
        }
コード例 #8
0
        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);
            }
        }
コード例 #9
0
        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);
        }
コード例 #13
0
        public ISecureCrypto CreateCrypto(SecurePassword password)
        {
            ISecureCrypto crypto = new SecureCrypto();

            crypto.Config.Password = password;

            return(crypto);
        }
コード例 #14
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         EventAggregator.Unsubscribe(this);
         SecurePassword?.Dispose();
     }
 }
コード例 #15
0
ファイル: NewUserViewModel.cs プロジェクト: punker76/PassMaid
        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;
 }
コード例 #17
0
        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
ファイル: SecurePassword.cs プロジェクト: OpenHark/HarkLib
        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
ファイル: Customer.cs プロジェクト: jbaldwin33/Bank
 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();
            }
        }
コード例 #26
0
        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
ファイル: App.xaml.cs プロジェクト: notour/WygwamToolkit
        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);
        }