コード例 #1
0
        public ActionResult SaveData(UserDetails userDetails)
        {
            ScryptEncoder      encode  = new ScryptEncoder();
            UserDetailsContext context = new UserDetailsContext();

            if (!ModelState.IsValid)
            {
                return(View("Index", userDetails));
            }

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



            if (userExistence == null)
            {
                ViewBag.UserAlreadyExists = "User Does Not Exists";
                return(View("Index"));
            }
            else if (!encode.Compare(userDetails.Password, userExistence.Password))
            {
                ViewBag.UserAlreadyExists = "Incorrect Password";
                return(View("Index"));
            }
            else if (encode.Compare(userDetails.Password, userExistence.Password))
            {
                Session["UserId"]   = userExistence.Id;
                Session["Email"]    = userExistence.Email;
                Session["UserName"] = userExistence.UserName;
                ViewBag.msg         = userExistence.UserName;
                return(RedirectToAction("Main", "Home"));
            }
            return(View("Index"));
        }
コード例 #2
0
        public ActionResult Login(LoginViewModel user)
        {
            ScryptEncoder   encode  = new ScryptEncoder();
            FixesAppContext context = new FixesAppContext();

            if (!ModelState.IsValid)
            {
                // return Content("call");
                return(View("Login", user));
            }

            var userExistence = context.Worker.SingleOrDefault(x => x.MobileNumber == user.MobileNumber);


            if (userExistence == null)
            {
                ViewBag.usernotexist = "User Does Not Exists";
                return(View("Login"));
            }
            else if (!encode.Compare(user.Password, userExistence.Password))
            {
                ViewBag.incorrectpassword = "******";
                return(View("Login"));
            }
            else if (encode.Compare(user.Password, userExistence.Password))
            {
                Session["workerId"] = userExistence.WorkerId;
                // ViewBag.msg = userExistence.UserName;
                Session["Mobile"] = user.MobileNumber;
                return(RedirectToAction("Main", "Worker"));
            }
            return(View("Login"));
        }
コード例 #3
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));
        }
コード例 #4
0
        public void TestBackwardCompatibility()
        {
            var encoder = new ScryptEncoder();

            var hashedPassword = "******";

            Assert.True(encoder.Compare("MyPassword", hashedPassword));

            hashedPassword = "******";
            Assert.True(encoder.Compare("MyPassword", hashedPassword));
        }
コード例 #5
0
        public bool ValidateUser(string email, string pass)
        {
            try
            {
                var u = myDb.Yoga_User.Where(x => x.U_Email == email).Single();

                bool isValidCustomer = encoder.Compare(pass, u.U_Password);

                return(isValidCustomer);
            }
            catch
            {
                return(false);
            }
        }
コード例 #6
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());
        }
コード例 #7
0
        public ActionResult Login(UserModel model)
        {
            ScryptEncoder encoder = new ScryptEncoder();

            try
            {
                var validUser = GetUser(model.UserName);

                if (validUser == null)
                {
                    ViewBag.result = "User email or password is invaild.";
                    return(View());
                }
                bool isValidUser = encoder.Compare(model.UserPassword, validUser.UserPassword);
                if (isValidUser)
                {
                    Session["userName"] = validUser.UserName;
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ViewBag.result = "User email or password is invaild.";
                    return(View());
                }
            }
            catch (Exception e)
            {
                ViewBag.Result = e.Message;
                return(View());
            }
        }
コード例 #8
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));
            }
            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"));
        }
コード例 #9
0
        public IActionResult LoginUser([FromBody] LoginCredentials credentials)
        {
            var user     = _dbCtx.UserAccounts.Where(x => x.AppUserName.Equals(credentials.Username)).FirstOrDefault();
            var response = new AuthResponse();

            if (user == null)
            {
                response.ResponseMessage = "Username is Incorrect or non-existent";
                return(new UnauthorizedObjectResult(response));
            }
            if (!_scryptHasher.Compare(credentials.Password, user.UserPassword))
            {
                response.ResponseMessage = "Password is Incorrect";
                return(new UnauthorizedObjectResult(response));
            }
            var token = _tokenManager.IssueToken(user);

            if (token.Equals(""))
            {
                response.ResponseMessage = "Failed to generate Authentication token";
                return(new NotFoundObjectResult(response));
            }
            response.ResponseMessage = "Successful Login";
            response.ResponseToken   = token;
            return(new OkObjectResult(response));
        }
コード例 #10
0
        public ActionResult Login(Users user)
        {
            // Note : Username and Password are same
            ScryptEncoder encoder = new ScryptEncoder();

            // Find the user valid or not, and also check the role is admin or not
            var acc = AllUsers.CheckUser(user.Username, Roles.Admin);

            if (acc != null)
            {
                bool areEquals = false;
                // Compare what u typed with the hashed password which are saved inside the database
                areEquals = encoder.Compare(user.Password, acc.Password);

                // Check the password correct or not
                if (areEquals != false)
                {
                    // After Login, i created two session to store id and username
                    Session["AdminID"]  = acc.ID;
                    Session["Username"] = acc.Username;
                    return(RedirectToAction("Users"));
                }
                else
                {
                    ViewbagError("Invalid Username or Password");
                }
                return(View());
            }
            else
            {
                ViewbagError("Invalid Username or Password");
            }
            return(View());
        }
        /// <inheritdoc />
        public PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
        {
            // check inputs
            if (string.IsNullOrEmpty(hashedPassword))
            {
                throw new ArgumentException(nameof(hashedPassword));
            }

            if (string.IsNullOrEmpty(providedPassword))
            {
                throw new ArgumentException(nameof(providedPassword));
            }

            // check password
            ScryptEncoder encoder = new ScryptEncoder();
            bool          isValid = encoder.Compare(providedPassword, hashedPassword);

            // return PasswordVerificationResult based on result of check
            if (isValid)
            {
                return(PasswordVerificationResult.Success);
            }

            return(PasswordVerificationResult.Failed);
        }
        public ActionResult Login(Users model)
        {
            ScryptEncoder encoder    = new ScryptEncoder();
            string        serviceUrl = string.Format("http://localhost:61866/EmployeeDetails.svc/GetUsers");

            byte[]       _data   = proxy.DownloadData(serviceUrl);
            Stream       _stream = new MemoryStream(_data);
            StreamReader reader  = new StreamReader(_stream);
            string       result  = reader.ReadToEnd();

            users = JsonConvert.DeserializeObject <List <Users> >(result);
            var Users     = users.AsQueryable();
            var ValidUser = (from c in users where c.UserName.Equals(model.UserName) select c).SingleOrDefault();

            if (ValidUser == null)
            {
                ModelState.AddModelError("", "invalid Username or Password");
                return(View());
            }
            bool isValidUser = encoder.Compare(model.Password, ValidUser.Password);

            if (isValidUser)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ViewBag.Error = "Username or password is invalid";
                return(RedirectToAction("Login"));
            }
        }
コード例 #13
0
        public ActionResult Login(Admin admin)
        {
            ViewBag.msg1 = admin.PasswordUs;
            if (String.IsNullOrEmpty(admin.UserNameUs) || String.IsNullOrEmpty(admin.PasswordUs))
            {
                return(View());
            }
            ScryptEncoder encoder = new ScryptEncoder();
            var           valid   = (from c in db.Admins where c.UserNameUs.Equals(admin.UserNameUs) select c).SingleOrDefault();

            if (db.Admins.All(x => x.UserNameUs != admin.UserNameUs))
            {
                ViewBag.Message1 = "The username " + admin.UserNameUs + " does not exists";
                return(View());
            }
            bool isvalid = encoder.Compare(admin.PasswordUs, valid.PasswordUs);

            if (valid != null && isvalid == true)
            {
                Session["IdUsSS"]     = admin.IdUs.ToString();
                Session["UserNameSS"] = admin.UserNameUs.ToString();
                return(RedirectToAction("LoginInfo", "Home"));
            }
            else if (admin.PasswordUs.Length < 6)
            {
                return(View());
            }
            else
            {
                ViewBag.Message1 = "Wrong Username or Password";
            }
            return(View());
        }
コード例 #14
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"));
        }
コード例 #15
0
        public ActionResult Logine(Employee_Login employee_Login)
        {
            ViewBag.msg1 = employee_Login.password;
            ScryptEncoder encoder = new ScryptEncoder();

            if (String.IsNullOrEmpty(employee_Login.id) || String.IsNullOrEmpty(employee_Login.password))
            {
                return(View());
            }
            else if (db.Employee_Login.All(x => x.id != employee_Login.id))
            {
                ViewBag.Notification1 = "This employee id " + employee_Login.id + " does not exists";
                return(View());
            }
            var  valid      = (from c in db.Employee_Login where c.id.Equals(employee_Login.id) select c).SingleOrDefault();
            var  checkLogin = db.Employee_Login.Where(x => x.id.Equals(employee_Login.id)).FirstOrDefault();
            bool isvalid    = encoder.Compare(employee_Login.password, valid.password);

            if (checkLogin != null && isvalid == true)
            {
                Session["IdUsSS1"] = employee_Login.id.ToString();
                //TempData["mydata"] =Session["IdUsSS1"];
                return(RedirectToAction("emphome", "Home"));
            }
            else if (employee_Login.password.Length < 6)
            {
                return(View());
            }
            else
            {
                ViewBag.Notification1 = "Incorrect Id or Password";
            }
            return(View());
        }
コード例 #16
0
        public bool VerifyPassword(string password, string hashedPassword)
        {
            ScryptEncoder encoder = new ScryptEncoder();
            bool          result  = encoder.Compare(password, hashedPassword);

            return(result);
        }
コード例 #17
0
        public async Task <IActionResult> Login(string username, string password)
        {
            try
            {
                ScryptEncoder scryptEncoder = new ScryptEncoder();
                usernameStatic = username;
                var admin = await _context.Admins.Where(x => x.AdminName.Equals(username)).FirstOrDefaultAsync();

                bool isAdmin = scryptEncoder.Compare(password, admin.AdminHash);

                if (isAdmin == true)
                {
                    HttpContext.Session.SetString("LoggedInAdmin", admin.AdminId.ToString());
                    return(View("Dashboard"));
                }
                else
                {
                    ViewBag.Error = "Username and password do not match!";
                    return(View());
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                return(View());
            }
        }
コード例 #18
0
        public bool VerifyPasswordHash(string password, [NotNull] byte[] storedHash)
        {
            var hashString = Encoding.UTF8.GetString(storedHash);

            var encoder = new ScryptEncoder();

            return(encoder.Compare(password, hashString));
        }
コード例 #19
0
 public PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword)
 {
     if (_encoder.Compare(providedPassword, hashedPassword))
     {
         return(PasswordVerificationResult.Success);
     }
     return(PasswordVerificationResult.Failed);
 }
コード例 #20
0
        public bool IsHashValid(string currentInput, string hashedInputWithSalt)
        {
            string saltString = hashedInputWithSalt.Substring(0, hashedInputWithSalt.Length - hashLength);
            string hashString = hashedInputWithSalt.Substring(hashedInputWithSalt.Length - hashLength, hashLength);

            ScryptEncoder encoder = new ScryptEncoder(16384, 8, 1);

            return(encoder.Compare(saltString + currentInput, hashString));
        }
コード例 #21
0
            /// <inheritdoc/>
            public override bool Compare(string hash)
            {
                if (digest != null)
                {
                    return(digest.Equals(hash));
                }
                ScryptEncoder scrypt = new ScryptEncoder(65536, 8, 1, ISecureRandomProvider.rngCryptoService);

                return(scrypt.Compare(input, hash));
            }
コード例 #22
0
        public bool Authenticate()
        {
            string ipAddress = this.GetIPAddress();

            string getCount = @"SELECT COUNT(id)
            FROM [dbo].[User]
            WHERE [username] = @username";

            int count = Convert.ToInt32(Database.Scalar(getCount, new System.Collections.Generic.Dictionary <string, object>
            {
                { "@username", this.Username }
            }));

            if (count < 1)
            {
                this.EnterLogin(ipAddress, true);
                return(false);
            }

            string getSalt = @"SELECT [salt]
            FROM [dbo].[User]
            WHERE [username] = @username";

            string salt = (string)Database.Scalar(getSalt, new System.Collections.Generic.Dictionary <string, object>
            {
                { "@username", this.Username }
            });

            string getHashed = @"SELECT [password]
                FROM [dbo].[User]
                WHERE [username] = @username";

            string hashed = (string)Database.Scalar(getHashed, new System.Collections.Generic.Dictionary <string, object>
            {
                { "@username", this.Username }
            });

            ScryptEncoder encoder        = new ScryptEncoder();
            bool          passwordsMatch = encoder.Compare(salt + this.EnteredPassword, hashed);

            if (passwordsMatch)
            {
                this.EnterLogin(ipAddress);

                // set up the static variables here
                this.SetupGlobalVars();

                return(true);
            }

            this.EnterLogin(ipAddress, true);

            return(false);
        }
コード例 #23
0
        public bool Check(string senha, string hash)
        {
            ScryptEncoder s = new ScryptEncoder();

            if (!s.IsValid(hash))
            {
                return(false);
            }

            return(s.Compare(senha, hash));
        }
コード例 #24
0
 //compare the user password for security
 public Boolean  VerifyPassword(string password = "", string hpassword = "")
 {
     try
     {
         return(encoder.Compare(password, hpassword));
     }
     catch (Exception)
     {
         throw;
     }
 }
コード例 #25
0
        public ActionResult Passupd(Admin admin)
        {
            using (DBuserSignupLoginEntities3 db = new DBuserSignupLoginEntities3())
            {
                ViewBag.msg1 = admin.PasswordUs;
                ViewBag.msg2 = admin.NewPasswordUs;
                ViewBag.msg3 = admin.ReNewPasswordUs;
                if (String.IsNullOrEmpty(admin.IdUs.ToString()) || String.IsNullOrEmpty(admin.PasswordUs) || String.IsNullOrEmpty(admin.NewPasswordUs) || String.IsNullOrEmpty(admin.ReNewPasswordUs) || admin.NewPasswordUs != admin.ReNewPasswordUs)
                {
                    return(View(admin));
                }
                else if (db.Admins.All(x => x.IdUs != admin.IdUs))
                {
                    ViewBag.Message1 = "The admin with id " + admin.IdUs + " does not exists";
                    return(View(admin));
                }
                var           valid   = (from c in db.Admins where c.IdUs.Equals(admin.IdUs) select c).SingleOrDefault();
                ScryptEncoder encoder = new ScryptEncoder();
                bool          isvalid = encoder.Compare(admin.PasswordUs, valid.PasswordUs);
                if (valid != null)
                {
                    Admin admin1 = db.Admins.Where(x => x.IdUs == admin.IdUs).FirstOrDefault();

                    if (admin1 != null && isvalid && admin.NewPasswordUs == admin.ReNewPasswordUs)
                    {
                        Admin  k  = db.Admins.Find(admin1.IdUs);
                        String s1 = admin1.UserNameUs;
                        db.Admins.Remove(k);
                        db.SaveChanges();
                        String k1 = admin.NewPasswordUs;
                        String k2 = encoder.Encode(k1);
                        db.Admins.Add(new Admin()
                        {
                            IdUs            = admin.IdUs,
                            UserNameUs      = s1,
                            PasswordUs      = k2,
                            NewPasswordUs   = k2,
                            RePasswordUs    = k2,
                            ReNewPasswordUs = k2
                        });

                        db.SaveChanges();
                        TempData["message"] = "Password for admin Id " + admin.IdUs + " has been updated successfully!";
                        return(RedirectToAction("Passupd", "Home"));
                    }
                    else
                    {
                        ViewBag.Message1 = "Old password is incorrect";
                    }
                }
            }
            return(View());
        }
コード例 #26
0
        public bool Verify(string plainText, string hashText)
        {
            ScryptEncoder encoder = new ScryptEncoder();

            if (encoder.Compare(plainText, hashText))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #27
0
ファイル: ScryptHash.cs プロジェクト: StevenLaw/DecryptorWpf
        public Task <bool> CheckHashAsync(string clearText, string hash)
        {
            ScryptEncoder encoder = new ScryptEncoder(_scryptIterations, _blockCount, _threadCount);

            try
            {
                return(Task.Run(() => encoder.Compare(clearText, hash)));
            }
            catch (ArgumentException)
            {
                return(Task.FromResult(false));
            }
        }
コード例 #28
0
        public void TestEncode()
        {
            int iterationCount = 2;

            for (int i = 0; i < 15; i++)
            {
                var encoder        = new ScryptEncoder(iterationCount, 8, 1);
                var hashedPassword = encoder.Encode("MyPassword");
                Assert.True(encoder.Compare("MyPassword", hashedPassword));

                iterationCount *= 2;
            }
        }
コード例 #29
0
ファイル: JwtController.cs プロジェクト: JeremyMoray/Pubeo
        public async Task <IActionResult> LoginParticulier([FromBody] DTO.LoginDTO loginDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var           authParticuliers = _context.Particuliers;
            ScryptEncoder encoder          = new ScryptEncoder();
            Particulier   particulierFound = authParticuliers.FirstOrDefault(par => par.Mail == loginDTO.Mail);

            if (particulierFound == null)
            {
                return(NotFound());
            }

            if (!encoder.Compare(loginDTO.MotDePasse, particulierFound.MotDePasse))
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, particulierFound.Mail),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat,
                          ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
                          ClaimValueTypes.Integer64),
            };

            // Create the JWT security token and encode it.
            JwtSecurityToken jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials
                );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);


            // Serialize and return the response
            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
            };

            return(Ok(response));
        }
コード例 #30
0
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage Request, CancellationToken CancelToken)
        {
            if (null != Request.Headers.Authorization)
            {
                // IF we have a "Basic" Authorization header, we need to login
                // ELSE we need to let the SessionToken cookie have a wack at it, so we do nothing
                if (Request.Headers.Authorization.Scheme.ToUpper() == "BASIC")
                {
                    string authData = Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter));

                    // Do Basic Auth
                    UserDataStore Users     = new UserDataStore();
                    IUser         FoundUser = (await Users.Get("EmailAddress", authData.Substring(0, authData.IndexOf(':')))).FirstOrDefault();

                    // EmailAddress is a unique key, so we can only find one
                    if (null != FoundUser)
                    {
                        ScryptEncoder scryptEncoder = new ScryptEncoder();

                        // IF Basic Auth Succeeds
                        if (scryptEncoder.Compare(Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)), FoundUser.PasswordHash))
                        {
                            // Set Principle
                            Thread.CurrentPrincipal = new GenericPrincipal(new DevSpaceIdentity(FoundUser), null);
                            Request.GetRequestContext().Principal = Thread.CurrentPrincipal;
                        }
                        // ELSE Basic Auth Fails
                        else
                        {
                            // return 401
                            return(new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized));
                        }
                    }

                    // Complete the request. We'll set the login cookie on the way out
                    HttpResponseMessage Response = await base.SendAsync(Request, CancelToken);

                    CookieHeaderValue SessionCookie = new CookieHeaderValue("SessionToken", (await Users.CreateSession((Thread.CurrentPrincipal.Identity as DevSpaceIdentity).Identity)).SessionToken.ToString());
#if DEBUG == false
                    SessionCookie.Secure = true;
#endif
                    SessionCookie.HttpOnly = true;
                    Response.Headers.AddCookies(new CookieHeaderValue[] { SessionCookie });

                    return(Response);
                }
            }

            return(await base.SendAsync(Request, CancelToken));
        }