public ActionResult NewPassword(FormCollection collection)
        {
            // SHould pass the user id in a safer way so that no one can modify the session id to change the password of someoneelse
            // hiddenfield instead of session Uid?

            int userId = Convert.ToInt32(Session["Uid"]);

            var user = db.getUserById(userId);

            String password1 = collection["password1"].ToString();
            String password2 = collection["password2"].ToString();

            //Validate password enter equal
            if (!string.Equals(password1, password2))
            {
                TempData["Message"] = "<h5 style=\"color:red;\">Please make sure the two passwords are the same</h5>";
                return(View());
            }

            user.U_Password = encoder.Encode(password2);
            user.Active     = true;

            db.UpdateUser(user);
            TempData["Message"] = "Your password was updated successfully.";


            //return View();
            return(RedirectToAction("MessageView", "Home"));
        }
示例#2
0
        public async Task <HttpResponseMessage> Post([ModelBinder(typeof(JsonUserBinder))] IUser NewUser)
        {
            if (null == NewUser)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            ScryptEncoder Hasher         = new ScryptEncoder();
            IUser         ExistingRecord = await _DataStore.Get(NewUser.Id);

            // Register new profile
            if (null == ExistingRecord)
            {
                await _DataStore.Add(NewUser.UpdatePasswordHash(Hasher.Encode(string.Format("{0}:{1}", NewUser.EmailAddress, NewUser.PasswordHash))));

                Email NewMail = new Email(NewUser.EmailAddress, NewUser.DisplayName);
                NewMail.Subject = "New Account Created";
                NewMail.Body    =
                    @"This email is to confirm the creation of your account on the DevSpace website.

If you did not create this account, please contact [email protected].";
                NewMail.Send();

                return(new HttpResponseMessage(HttpStatusCode.Created));
            }

            // You can only post a new profile if you're not authenticated
            if (!Thread.CurrentPrincipal?.Identity?.IsAuthenticated ?? true)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            // You can only update yourself
            if (!(Thread.CurrentPrincipal.Identity as DevSpaceIdentity).Identity.Id.Equals(NewUser.Id))
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            if (!string.IsNullOrWhiteSpace(NewUser.PasswordHash))
            {
                NewUser = NewUser.UpdatePasswordHash(Hasher.Encode(string.Format("{0}:{1}", NewUser.EmailAddress, NewUser.PasswordHash)));
            }

            await _DataStore.Update(NewUser);

            Email UpdateMail = new Email(NewUser.EmailAddress, NewUser.DisplayName);

            UpdateMail.Subject = "Account Updated";
            UpdateMail.Body    =
                @"This email is to confirm your account on the DevSpace website was updated.

If you did not update this account, please contact [email protected].";
            UpdateMail.Send();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
示例#3
0
        //zrób validację hasła czy wystarczy
        public Result <User> Add(RegisterUserModel item, bool IsTemporary = false)
        {
            //if (!_userRepository.UserExist(item.Login))
            //{
            int userType = (int)AuthorizationEnum.NormalUser;//normal user

            if (IsTemporary)
            {
                userType = (int)AuthorizationEnum.TemporaryUser;
            }

            if (_userRepository.IsFirstUser())
            {
                userType = (int)AuthorizationEnum.AdminUser; //admin
            }
            ScryptEncoder encoder = new ScryptEncoder();
            User          u       = new User()
            {
                UserTypeId = userType, Password = encoder.Encode(item.Password), Login = item.Login, Email = item.Email, FirstName = item.FirstName, Surname = item.Surname, PhoneNumber = item.PhoneNumber
            };

            return(retWithoutPassword(_userRepository.Add(u)));
            //}
            //var r = new Result<User>();
            //r.info = "taki użytkownik istnieje";
            //r.status = false;
            //return r;
        }
示例#4
0
        public bool Update()
        {
            if (this.NewPassword)
            {
                this.Salt = this.CreateSalt();
                ScryptEncoder encoder = new ScryptEncoder();
                this.Password = encoder.Encode(this.Salt + this.Password);
            }

            string sql = @"UPDATE [dbo].[User]
            SET [username] = @username
               ,[password] = @password
               ,[salt] = @salt
               ,[email] = @email
            WHERE [id] = @id";

            return(Database.Non(sql, new System.Collections.Generic.Dictionary <string, object>
            {
                { "@username", this.Username },
                { "@password", this.Password },
                { "@salt", this.Salt },
                { "@email", this.Email },
                { "@id", this.Id }
            }));
        }
示例#5
0
        public bool Create()
        {
            this.Salt = this.CreateSalt();
            ScryptEncoder encoder = new ScryptEncoder();

            this.Password = encoder.Encode(this.Salt + this.Password);

            string sql = @"INSERT INTO [dbo].[User] ([username],
              [password],
              [salt],
              [email])
            VALUES (
              @username
             ,@password
             ,@salt
             ,@email
            )";

            return(Database.Non(sql, new System.Collections.Generic.Dictionary <string, object>
            {
                { "@username", this.Username },
                { "@password", this.Password },
                { "@salt", this.Salt },
                { "@email", this.Email },
            }));
        }
示例#6
0
        public ActionResult Register(RegisterViewModel registerViewModel)
        {
            ScryptEncoder      encode  = new ScryptEncoder();
            UserDetailsContext context = new UserDetailsContext();

            if (!ModelState.IsValid)
            {
                return(View("SignUp", registerViewModel));
            }

            var userExistence = context.UserDetails.SingleOrDefault(x => x.Email == registerViewModel.UserDetails.Email);

            if (userExistence != null)
            {
                ViewBag.UserAlreadyExists = "User Already Exists";
                return(View("SignUp", registerViewModel));
            }
            if (registerViewModel.ConfirmPassword != registerViewModel.UserDetails.Password)
            {
                ViewBag.UserAlreadyExists = "Password And Confirm Password Mismatch";
                return(View("SignUp", registerViewModel));
            }
            registerViewModel.UserDetails.Password = encode.Encode(registerViewModel.UserDetails.Password);
            registerViewModel.UserDetails.UserName = "******";
            context.UserDetails.Add(registerViewModel.UserDetails);
            context.SaveChanges();
            // @ViewBag.success = "Account Created Succesfully Login to continue";
            this.AddNotification("Account Created Succesfully Login to continue", NotificationType.SUCCESS);
            return(View("SignUp"));
        }
示例#7
0
        private Professionnel Modification(Professionnel initialPro, ProfessionnelsUpdateDTO targetPro)
        {
            ScryptEncoder encoder = new ScryptEncoder();
            var           retour  = initialPro;

            if (targetPro.NomEntreprise != null)
            {
                retour.NomEntreprise = targetPro.NomEntreprise;
            }
            if (targetPro.Adresse != null)
            {
                retour.Adresse = targetPro.Adresse;
            }
            if (targetPro.MotDePasse != null)
            {
                retour.MotDePasse = encoder.Encode(targetPro.MotDePasse);
            }
            if (targetPro.NumeroTel != null)
            {
                retour.NumeroTel = targetPro.NumeroTel;
            }
            if (targetPro.Mail != null)
            {
                retour.Mail = targetPro.Mail;
            }
            if (targetPro.NumeroTVA != null)
            {
                retour.NumeroTVA = targetPro.NumeroTVA;
            }
            if (targetPro.LocaliteCode != null)
            {
                retour.LocaliteCode = targetPro.LocaliteCode;
            }
            return(retour);
        }
示例#8
0
        public ActionResult CambiarContraseñaUsers(Password changePass)
        {
            if (ModelState.IsValid)
            {
                ScryptEncoder encoder  = new ScryptEncoder();
                Usuarios      usuarios = db.Usuarios.Find(changePass.idU);

                bool Validar = encoder.Compare(changePass.oldPass, usuarios.hash_password);
                if (Validar)
                {
                    usuarios.hash_password   = encoder.Encode(changePass.newPass);
                    db.Entry(usuarios).State = EntityState.Modified;
                    db.SaveChanges();
                    TempData["Success"] = "¡Contraseña modificada, por favor ingrese nuevamente!";
                    return(RedirectToAction("Cerrar", "Acceso"));
                }
                else
                {
                    ViewBag.Error = "¡Las contraseñas no coinciden!";
                    return(View());
                }
            }

            ViewBag.Error = "¡Ha ocurrido un error, intenta nuevamente!";
            return(View());
        }
示例#9
0
        public int AddUser(UserTable users)
        {
            try
            {
                users.UserRole = new List <UserRole>();
                UserRole      roles           = new UserRole();
                ScryptEncoder encoder         = new ScryptEncoder();
                string        encodedPassword = encoder.Encode(users.Password).ToString();
                users.Password = encodedPassword;
                roles.Role     = "Employee";
                roles.UserId   = users.Id;
                users.UserRole.Add(roles);

                foreach (UserRole role in users.UserRole)
                {
                    UserTable user = new UserTable();
                    role.UserId   = users.Id;
                    user.UserName = users.UserName;
                    user.Password = users.Password;
                }
                db.UserTable.Add(users);
                db.SaveChanges();
            }

            catch (Exception ex)
            {
                throw ex;
            }
            return(users.Id);
        }
示例#10
0
        private string GetHash(string salt, string password)
        {
            var    passwordToHash  = GetSaltedAndPepperedPassword(salt, password);
            string hashsedPassword = _encoder.Encode(passwordToHash);

            return(hashsedPassword);
        }
示例#11
0
        public string CreatePasswordHash(string password)
        {
            ScryptEncoder encoder        = new ScryptEncoder();
            string        hashedPassword = encoder.Encode(password);

            return(hashedPassword);
        }
示例#12
0
        public async Task <IActionResult> Register(RegisterModel registerModel)
        {
            if (ModelState.IsValid)
            {
                var users = await _context.GetCollection();

                User user = users.FirstOrDefault(u => u.Email == registerModel.Email);
                if (user == null)
                {
                    var randomWord = GenerateRandomWord();
                    var secretWord = Configuration.GetSection("PasswordStrings").GetSection("EndWord").Value;
                    var password   = _scryptEncoder.Encode(registerModel.Password + randomWord + secretWord);
                    user = new User()
                    {
                        Name       = registerModel.Name,
                        Password   = password,
                        Email      = registerModel.Email,
                        RandomWord = randomWord
                    };
                    _notificationSender.Send("Welcome to our system!", user.Email);
                    await _context.Create(user);
                    await Authenticate(user.Email);

                    return(RedirectToAction("Index", "Main"));
                }
                else
                {
                    ModelState.AddModelError("", "Данная почта занята");
                }
                // await _context.Remove(user.Id);
            }
            return(View("Authorization"));
        }
示例#13
0
        async Task addUser(string login, string password, byte level)
        {
            if ((textBoxLogin.TextLength != 0) && (textBoxPassword.TextLength != 0))
            {
                ScryptEncoder encoder     = new ScryptEncoder();
                string        hashedPassw = encoder.Encode(password);
                string[]      lines;
                if (!File.Exists(path))
                {
                    MessageBox.Show("File not found.");
                }
                else
                {
                    lines = File.ReadAllLines(path);
                    if (!checkLogin(lines, login))
                    {
                        using (FileStream fstream = new FileStream(path, FileMode.Append))
                        {
                            byte[] array = System.Text.Encoding.Default.GetBytes(login + ":" + hashedPassw + ":" + level + Environment.NewLine);
                            // асинхронная запись массива байтов в файл
                            await fstream.WriteAsync(array, 0, array.Length);

                            fstream.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Пользователь с таким логином существует.");
                    }
                }
            }
        }
示例#14
0
        public void TestIsValid()
        {
            var encoder = new ScryptEncoder();

            Assert.False(encoder.IsValid("$e1$adasdasd$asdasdsd"));
            Assert.True(encoder.IsValid(encoder.Encode("MyPassword")));
        }
示例#15
0
        public byte[] CalculatePasswordHash(string password, [CanBeNull] byte[] associatedData = null)
        {
            var encoder = new ScryptEncoder();
            var hash    = encoder.Encode(password);

            return(Encoding.UTF8.GetBytes(hash));
        }
示例#16
0
        public ActionResult ChangePassword(string username, string currentPass, string newPass, string confirmPass)
        {
            if (username == null || currentPass == null || newPass == null || confirmPass == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ScryptEncoder encoder     = new ScryptEncoder();
            var           user        = db.Users.Find(username);
            bool          isValidPass = encoder.Compare(currentPass, user.Password);

            if (!isValidPass)
            {
                TempData["Current_Pass_Fail"] = true;
                return(RedirectToAction("Index"));
            }
            if (newPass != confirmPass)
            {
                TempData["Password_Not_Match"] = true;
                return(RedirectToAction("Index"));
            }

            user.Password = encoder.Encode(newPass);
            if (db.SaveChanges() > 0)
            {
                TempData["Notice_Save_Success"] = true;
            }
            return(RedirectToAction("Index"));
        }
        public ActionResult ChangePassword(string username, string currentPass, string newPass, string confirmPass)
        {
            if (username == null || currentPass == null || newPass == null || confirmPass == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            if (newPass != confirmPass)
            {
                TempData["Error"] = "Confirmation password does not match!";
                return(RedirectToAction("ChangePassword"));
            }

            ScryptEncoder encoder     = new ScryptEncoder();
            var           user        = db.Users.Find(username);
            bool          isValidPass = encoder.Compare(currentPass, user.Password);

            if (!isValidPass)
            {
                TempData["Error"] = "Current password is incorrect!";
                return(RedirectToAction("ChangePassword"));
            }


            user.Password = encoder.Encode(newPass);
            if (db.SaveChanges() > 0)
            {
                TempData["SuccessMess"] = "Update successful";
            }
            return(RedirectToAction("ChangePassword"));
        }
示例#18
0
        public ActionResult SignUp(CustomerModel model)
        {
            ScryptEncoder encoder = new ScryptEncoder();

            if (model.Email == null)
            {
                ModelState.AddModelError("Email", "Required");
            }
            if (model.Password == null)
            {
                ModelState.AddModelError("Password", "Required");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    int affectedRows = CustomerRegister(
                        model.FirstName,
                        model.LastName,
                        model.Address,
                        model.City,
                        model.Province,
                        model.Postal,
                        model.Country,
                        model.HomePhone,
                        model.BusinessPhone,
                        model.Email,
                        encoder.Encode(model.Password)
                        );
                    if (affectedRows > 0)
                    {
                        ViewBag.Result = "Registered successfully. You can login now.";
                        return(View());
                    }
                    else
                    {
                        ViewBag.result = "The email address is already registered.";
                    }
                }
                catch (Exception e)
                {
                    ViewBag.Result = e.Message;
                }
            }

            List <Country> CountryList = LoadCountry();

            ViewBag.CountryList = new SelectList(CountryList, "CountryName", "CountryName");

            if (model.Country != null)
            {
                List <Province> ProvinceList = LoadProvince(model.Country);
                ViewBag.ProvinceList = new SelectList(ProvinceList, "ProvAbbr", "ProvName");
            }
            model.Password        = null;
            model.ConfirmPassword = null;
            return(View(model));
        }
示例#19
0
        /// <summary>
        /// Start this instance.
        /// </summary>
        public void Start()
        {
            //https://stackoverflow.com/questions/2586612/how-to-keep-a-net-console-app-running
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                _quitEvent.Set();
                eArgs.Cancel = true;
            };

            //Connect and create users collection for LiteDB.org
            //Get users collection
            var col = db.GetCollection <Users>("users");

            if (col.Count() == 0)
            {
                ScryptEncoder encoder         = new ScryptEncoder();
                string        hashsedPassword = encoder.Encode("test1234!");
                //Console.WriteLine(hashsedPassword);
                //Same password
                //string hashsedPassword2 = encoder.Encode("test1234!");
                //Console.WriteLine(hashsedPassword);
                // Create your new customer instance
                var user = new Users
                {
                    UserName     = "******",
                    UserPassword = hashsedPassword,
                    IsActive     = true
                };

                // Create unique index in Name field
                col.EnsureIndex(x => x.UserName, true);

                // Insert new customer document (Id will be auto-incremented)
                col.Insert(user);
            }

            NetworkEndPoint    endPoint = new NetworkEndPoint(IPAddress.Any, portNumber);
            ConnectionListener listener = new UdpConnectionListener(endPoint);

            Running = true;

            Console.WriteLine("Starting server!");
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;

            Console.WriteLine("Server Version: " + version);
            Console.WriteLine("BD file path: " + Path.Combine(AssemblyDirectory, @"UsersObjects.db"));
            Console.WriteLine("Server listening on " + (listener as UdpConnectionListener).EndPoint);
            listener.NewConnection += NewConnectionHandler;
            listener.Start();

            _quitEvent.WaitOne();

            //Close all
            listener.Close();
            //Exit 0
            Environment.Exit(0);
        }
示例#20
0
        public void TestCompare()
        {
            var encoder        = new ScryptEncoder();
            var hashedPassword = encoder.Encode("MyPassword");

            Assert.True(encoder.Compare("MyPassword", hashedPassword));
            Assert.False(encoder.Compare("WrongPassword", hashedPassword));
        }
示例#21
0
        /// <summary>
        /// This hash function will auto generate a salt. Each call to the function will result in a different value. Need to use the ScryptIsMatch Method
        /// </summary>
        /// <param name="toHash"></param>
        /// <returns></returns>
        public static string Scrypt(string toHash)
        {
            ScryptEncoder encod = new ScryptEncoder();

            string hash = encod.Encode(toHash);

            return(hash);
        }
示例#22
0
        public BL_Result <User> Register(RegisterViewModel registerViewModel)
        {
            User user = repo_user.Find(x => x.Email == registerViewModel.Email);

            if (user != null)
            {
                result_user.addError(ErrorMessages.RegisteredUser, "Kayıtlı kullanıcı");
            }
            else
            {
                // db_zeynerp user ekleme işlemi
                string scryptPassword = scryptEncoder.Encode(registerViewModel.Password);
                string companyId      = Guid.NewGuid().ToString().Substring(0, 8);

                int db = repo_user.Insert(new User()
                {
                    Name        = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(registerViewModel.Name),
                    Surname     = registerViewModel.Surname.ToUpper(),
                    Email       = registerViewModel.Email,
                    Password    = scryptPassword,
                    Repassword  = scryptPassword,
                    IsAdmin     = false,
                    IsActive    = false,
                    CompanyName = registerViewModel.CompanyName.ToUpper(),
                    CompanyId   = companyId,
                    Birthday    = DateTime.Now,
                    Guid        = Guid.NewGuid()
                });

                if (db > 0)
                {
                    result_user.Result = repo_user.Find(x => x.Email == registerViewModel.Email);
                }

                // Mail işlemleri
                string body = "Hello " + result_user.Result.Name + ",";
                body += "<br /><br />Please click the following link to activate your account";
                body += "<br /><a href = '" + string.Format("{0}://{1}/Home/Activation/{2}", "https", "zeynerp.com", result_user.Result.Guid) + "'>Click here to activate your account.</a>";
                //body += "<br /><a href = '" + string.Format("{0}://{1}/Home/Activation/{2}", "https", "zeynerp.com", result_user.Result.Guid) + "'>Click here to activate your account.</a>";
                body += "<br /><br />Thanks";

                MailHelper mailHelper = new MailHelper();
                mailHelper.SendMail(result_user.Result.Email, body);
            }
            return(result_user);
        }
示例#23
0
        // Méthode faisant le hashage du mot de passe
        private string FaireHashage(string MDP, int num)
        {
            ScryptEncoder encoder       = new ScryptEncoder();
            String        MDPHacher     = encoder.Encode(MDP);
            String        MDPSaleHacher = getSalage(num) + MDPHacher;

            return(MDPSaleHacher);
        }
示例#24
0
        public async Task <string> GetFileHashAsync(string filename)
        {
            var bytes = await File.ReadAllBytesAsync(filename);

            ScryptEncoder encoder   = new ScryptEncoder(_scryptIterations, _blockCount, _threadCount);
            var           clearText = Encoding.Default.GetString(bytes);

            return(encoder.Encode(clearText));
        }
示例#25
0
 /// <summary>
 /// Computes the digest of the specified input string using the Scrypt hash function as implemented by the <see cref="ScryptEncoder"/> and a random salt.
 /// </summary>
 /// <returns>The hex encoded, salted scrypt hash of the input string.</returns>
 public override string ComputeHash()
 {
     if (digest == null)
     {
         ScryptEncoder scrypt = new ScryptEncoder(65536, 8, 1, ISecureRandomProvider.rngCryptoService);
         digest = scrypt.Encode(input);
     }
     return(digest);
 }
示例#26
0
        public async Task <string> GetHashAsync(Stream stream)
        {
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);

            ScryptEncoder encoder   = new ScryptEncoder(_scryptIterations, _blockCount, _threadCount);
            var           clearText = Encoding.Default.GetString(ms.ToArray());

            return(encoder.Encode(clearText));
        }
示例#27
0
        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            //Connect and create users collection for LiteDB.org
            //LiteDB connection
            LiteDatabase db = new LiteDatabase(@"UsersObjects.db");

            //Get users collection
            var col = db.GetCollection <Users>("users");

            //Create Scrypt Password
            ScryptEncoder encoder         = new ScryptEncoder();
            string        hashsedPassword = encoder.Encode(SecondValue);

            if (col.Count() == 0)
            {
                // Create your new customer instance
                var user = new Users
                {
                    UserName     = FirstValue,
                    UserPassword = hashsedPassword,
                    IsActive     = true
                };

                // Create unique index in Name field
                col.EnsureIndex(x => x.UserName, true);

                // Insert new customer document (Id will be auto-incremented)
                col.Insert(user);
                ShowInfo(host, hashsedPassword);
            }
            else
            {
                // Create your new customer instance
                var user = new Users
                {
                    UserName     = FirstValue,
                    UserPassword = hashsedPassword,
                    IsActive     = true
                };

                // Insert new customer document (Id will be auto-incremented)
                try
                {
                    col.Insert(user);
                    ShowInfo(host, hashsedPassword);
                }
                catch (LiteDB.LiteException e)
                {
                    host.WriteMessage("ERROR: " + e.Message);
                    host.WriteMessage("\n");
                }
            }
            return(null);
        }
示例#28
0
        protected void buttonSCRYPT_Click(object sender, EventArgs e)
        {
            if (passwordNotEnteredError())
            {
                return;
            }

            ScryptEncoder encoder = new ScryptEncoder();

            Response.Write($"Your SCRYPT encryption is {encoder.Encode(TextBox1.Text)}");
        }
示例#29
0
        public string GenerateHash(string input)
        {
            string salt = GenerateRNG(16, 32);

            // calculate iterationCount = 16384, blockSize = 8, threadCount = 1
            ScryptEncoder encoder             = new ScryptEncoder(16384, 8, 1);
            string        inputWithSaltString = salt + input;
            string        hashedInputWithSalt = salt + encoder.Encode(inputWithSaltString);

            return(hashedInputWithSalt);
        }
示例#30
0
        //hash the user account password to protected value

        public string HashPassword(string password = "")
        {
            try
            {
                string hpassword = encoder.Encode(password);
                return(hpassword);
            }
            catch (Exception e)
            {
                return(e.Message.ToString());
            }
        }