Golang code-google-com-p-go-crypto-bcrypt.CompareHashAndPassword类(方法)实例源码

下面列出了Golang code-google-com-p-go-crypto-bcrypt.CompareHashAndPassword 类(方法)源码代码实例,从而了解它的用法。

作者:RodrigoDe    项目:gondal   
func (suite *HandlerUtilsTestSuite) TestChangePassword(c *C) {
	TRACE.Println("Running test: TestChangePassword")
	tx := dbConnection.Begin()

	testString := "UniqueTestUser123321"

	testCreateUserRequest := CreateUserRequest{Username: testString, LegalName: testString, Password: testString}
	status, err := CreateNewUser(testCreateUserRequest, tx)

	c.Assert(err, IsNil)
	c.Assert(status, Equals, 200)

	var testUser User

	tx.Where(&User{UserName: testString}).Find(&testUser)

	compareErr := bcrypt.CompareHashAndPassword([]byte(testUser.Password), []byte(testString))
	c.Assert(compareErr, IsNil)

	newPassword := "newPassword"
	changePasswordStatus, changePasswordErr := ChangePassword(testString, newPassword, tx)
	c.Assert(changePasswordErr, IsNil)
	c.Assert(changePasswordStatus, Equals, 200)

	tx.Where(&User{UserName: testString}).Find(&testUser)

	compareErr = bcrypt.CompareHashAndPassword([]byte(testUser.Password), []byte(newPassword))
	c.Assert(compareErr, IsNil)

	changePasswordStatusUnregisteredUser, changePasswordErrUnregisteredUser := ChangePassword("unregisteredUser123321", newPassword, tx)
	c.Assert(changePasswordErrUnregisteredUser, Equals, UnregisteredUser)
	c.Assert(changePasswordStatusUnregisteredUser, Equals, 401)

	tx.Rollback()
}

作者:pc    项目:influxd   
// Ensure the server can create a new user.
func TestServer_CreateUser(t *testing.T) {
	s := OpenServer(NewMessagingClient())
	defer s.Close()

	// Create a user.
	if err := s.CreateUser("susy", "pass", true); err != nil {
		t.Fatal(err)
	}
	s.Restart()

	// Verify that the user exists.
	if u := s.User("susy"); u == nil {
		t.Fatalf("user not found")
	} else if u.Name != "susy" {
		t.Fatalf("username mismatch: %v", u.Name)
	} else if !u.Admin {
		t.Fatalf("admin mismatch: %v", u.Admin)
	} else if bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte("pass")) != nil {
		t.Fatal("invalid password")
	}

	// Verify that the authenticated user exists.
	u, err := s.Authenticate("susy", "pass")
	if err != nil {
		t.Fatalf("error fetching authenticated user")
	} else if u.Name != "susy" {
		t.Fatalf("username mismatch: %v", u.Name)
	} else if !u.Admin {
		t.Fatalf("admin mismatch: %v", u.Admin)
	} else if bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte("pass")) != nil {
		t.Fatal("invalid password")
	}

}

作者:PayPal-OpportunityHack-BLR-201    项目:bloodcare-hif   
func AuthAdmin(email, pass string, db *services.MySQL) (*Admin, *app.Msg, error) {
	const (
		ADMIN_AUTH_SQL = "SELECT id, name, password, status  FROM admin_users WHERE email=?"
	)
	var id, name, bcryptpass, status string

	if len(email) == 0 || len(pass) == 0 {
		return nil, app.NewErrMsg("The email or password is empty."), nil
	}

	rows, err := db.Query(ADMIN_AUTH_SQL, email)
	if err != nil {
		return nil, nil, err
	}
	defer rows.Close()

	if !rows.Next() {
		return nil, app.NewErrMsg("The email or password is incorrect."), nil
	}

	rows.Scan(&id, &name, &bcryptpass, &status)
	perr := bcrypt.CompareHashAndPassword([]byte(bcryptpass), []byte(pass))
	if perr != nil {
		return nil, app.NewErrMsg("The email or password is incorrect."), nil
	}
	if status == "inactive" {
		return nil, app.NewErrMsg("Please contact sysadmin"), nil
	}
	return &Admin{ID: id, Name: name, Email: email}, nil, nil
}

作者:vichetu    项目:gobo   
func ValidateUserPassword(email, password string) (user structs.User, err error) {
	model.DB.Where("email = ?", email).First(&user)
	bytePassword := []byte(password)
	byteHash := []byte(user.HashedPassword)
	err = bcrypt.CompareHashAndPassword(byteHash, bytePassword)
	return user, err
}

作者:huntau    项目:lis   
// Login a User
func (u *Users) Login(email string, password string) revel.Result {
	// Grab User with Email
	var user *models.User
	err := users.Find(map[string]string{"email": email}).One(&user)
	if err != nil {
		u.Flash.Error("Incorrect username or password.")
		return u.Redirect(routes.App.Index())
	}

	// Check Passwords
	bytes, _ := hex.DecodeString(user.HashedPassword)
	if bcrypt.CompareHashAndPassword(bytes, []byte(password)) != nil {
		u.Flash.Error("Incorrect username or password.")
		return u.Redirect(routes.App.Index())
	}

	// Only login if they are verified
	if user.Verified {
		u.Session["user"] = email
	} else {
		u.Flash.Error("You cannot login until you verify your email.")
	}

	return u.Redirect(routes.App.Index())
}

作者:kmeistha    项目:sakubu   
func (u PasswordCredential) CheckPassword(password []byte) bool {
	if bcrypt.CompareHashAndPassword(u.PassHash, password) == nil {
		return true
	} else {
		return false
	}
}

作者:zuwik    项目:hella   
func (player *Player) CheckPassword(password string) bool {
	e := bcrypt.CompareHashAndPassword(bytes.NewBufferString(player.PasswordHash).Bytes(), bytes.NewBufferString(password).Bytes())
	if e == nil {
		return true
	}
	return false
}

作者:fornd    项目:bytengin   
func ValidatePassword(pwh, pw []byte) bool {
	err := bcrypt.CompareHashAndPassword(pwh, pw)
	if err != nil {
		return false
	}
	return true
}

作者:RodrigoDe    项目:gondal   
func (suite *HandlerUtilsTestSuite) TestCreateNewUserWithUniqueUsername(c *C) {
	TRACE.Println("Running test: TestCreateNewUserWithUniqueUsername")

	tx := dbConnection.Begin()

	testString := "UniqueTestUser123321"

	var testCreateUserRequest CreateUserRequest
	testCreateUserRequest.Username = testString
	testCreateUserRequest.LegalName = testString
	testCreateUserRequest.Password = testString

	status, err := CreateNewUser(testCreateUserRequest, tx)

	c.Check(err, IsNil)
	c.Assert(status, Equals, 200)

	var user User

	dbErr := tx.Where(&User{UserName: testString}).First(&user).Error
	c.Assert(dbErr, IsNil)
	comparePasswordErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(testString))
	c.Assert(comparePasswordErr, IsNil)

	var passwordRecord PasswordRecord
	tx.Where(&PasswordRecord{UserId: user.Id}).Find(&passwordRecord)
	c.Assert(passwordRecord.LoginCount, Equals, 0)

	tx.Rollback()
}

作者:rajasau    项目:sync_gatewa   
// Optimized wrapper around bcrypt.CompareHashAndPassword that caches successful results in
// memory to avoid the _very_ high overhead of calling bcrypt.
func compareHashAndPassword(hash []byte, password []byte) bool {
	// Actually we cache the SHA1 digest of the password to avoid keeping passwords in RAM.
	s := sha1.New()
	s.Write(password)
	digest := string(s.Sum(nil))
	key := digest + string(hash)

	cacheLock.Lock()
	_, valid := cachedHashes[key]
	cacheLock.Unlock()
	if valid {
		return true
	}

	// Cache missed; now we make the very slow (~100ms) bcrypt call:
	if err := bcrypt.CompareHashAndPassword(hash, password); err != nil {
		// Note: It's important to only cache successful matches, not failures.
		// Failure is supposed to be slow, to make online attacks impractical.
		return false
	}

	cacheLock.Lock()
	if len(cachedHashes) >= kMaxCacheSize {
		cachedHashes = map[string]struct{}{}
	}
	cachedHashes[key] = struct{}{}
	cacheLock.Unlock()
	return true
}

作者:Chandle    项目:gofles   
/*
Endpoint: given email (or screen_name) + password,
return user_id and api_key
*/
func (c *Users) Authenticate() revel.Result {
	var authInfo UserAuthenticateInput
	data, err := ioutil.ReadAll(c.Request.Body)
	if err := json.Unmarshal([]byte(data), &authInfo); err != nil {
		return c.RenderError(err)
	}

	authInfo.Email = strings.ToLower(authInfo.Email)

	user, err := authInfo.Model()
	if err != nil {
		c.Response.Status = 401
		return c.RenderError(err)
	}

	out := UserAuthenticateOutput{user.Id, user.Api_key}

	if authInfo.Api_key == user.Api_key { // TODO: fix client-side auth so we don't have this hack
		return c.RenderJson(out)
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authInfo.Password))

	if err != nil {
		c.Response.Status = 401
		return c.RenderText("")
	}

	return c.RenderJson(out)
}

作者:klyde    项目:dogfor   
/*
Attempts to authenticate a user and returns a JWT if successful
*/
func (ud UserDomain) Authenticate(ar *AuthenticationRequest) (*string, error) {
	u := User{}

	err := ud.Collection.Find(bson.M{"username": ar.Username}).One(&u)

	if err != nil {
		return nil, err
	}

	// check password against hash
	err = bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(ar.Password))

	if err != nil {
		return nil, fmt.Errorf("Invalid password for %s", ar.Username)
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))

	token.Header["user_id"] = u.Uid
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

	// TODO!  move this signing key to .env (and maybe use rsa key)
	tokenString, err := token.SignedString([]byte("dogfort"))

	if err != nil {
		return nil, err
	} else {
		return &tokenString, nil
	}
}

作者:jango201    项目:baseap   
func (c Account) LoginAccount(account, password string, remember bool) r.Result {

	var profile *models.Profile

	// If account is a valid email address, retrieve account by email
	// otherwise, retrieve account by username
	models.ValidateUserEmail(c.Validation, account).Key("account")

	if c.Validation.HasErrors() {
		c.Validation.Clear()
		profile = c.getProfileByUserName(account)
	} else {
		profile = c.getProfileByEmailAddress(account)
	}

	if profile != nil {
		err := bcrypt.CompareHashAndPassword(profile.User.HashedPassword, []byte(password))
		if err == nil {
			c.DoLogin(profile.User, remember)
			c.Flash.Success("Welcome back, " + profile.Name)
			return c.Redirect(routes.Profile.Show(profile.UserName))
		}
	}

	c.Flash.Error("Sign In failed.")
	return c.Redirect(routes.Account.Login())
}

作者:pcie    项目:san   
func equal(encryption, password []byte) bool {
	err := bcrypt.CompareHashAndPassword(encryption, password)
	if err != nil {
		return false
	}
	return true
}

作者:pavbe    项目:bcryptplu   
// Checks if the password matches the hash
//
// If the cost of the given hash is below the cost we currently use, the 2nd return value will contain a new and stronger hash.
// If the 2nd return value is present, you must update the hash for the password to it or you're missing out on the security benefits and wasting CPU cycles.
// If the given hash is already strong enough, the 2nd argument will be nil.
func (self *Hasher) Validate(password []byte, hash []byte) (bool, []byte, error) {
	err := bcrypt.CompareHashAndPassword(hash, password)

	if err != nil {
		// password and hash do not match
		return false, nil, nil
	} else {
		// password matches the hash

		costOfHash, err := bcrypt.Cost(hash)

		if err != nil || costOfHash < self.currentCost {
			// if unable to determine the cost (err != nil), treat it the same as an outdated hash

			newHash, err := self.Hash(password)

			if err != nil {
				return true, nil, err
			} else {
				return true, newHash, nil
			}
		} else {
			// the hash is valid and is sufficiently strong
			return true, nil, nil
		}
	}
}

作者:rualatngu    项目:tsur   
func (s *S) TestUserCheckPasswordUsesBcrypt(c *gocheck.C) {
	u := auth.User{Email: "paradisum", Password: "abcd1234"}
	err := hashPassword(&u)
	c.Assert(err, gocheck.IsNil)
	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte("abcd1234"))
	c.Assert(err, gocheck.IsNil)
}

作者:nilsnanse    项目:greylo   
func dbauthenticate(username, password string) error {
	var passhash string

	stmt, err := db.Prepare(`
	select passhash from user where username = ?;
	`)

	if err != nil {
		panic(err)
	}

	stmt.Exec(username)
	if !sql.Must(stmt.Next()) {
		return errors.New("No such user.")
	}

	err = stmt.Scan(&passhash)
	if err != nil {
		panic(err)
	}

	err = bcrypt.CompareHashAndPassword([]byte(passhash), []byte(password))

	return err
}

作者:hypertornad    项目:prag   
func (u *User) isPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		return false
	}
	return true
}

作者:qap    项目:goblog-playgroun   
func UserLogin(r *http.Request, db *sql.DB, s sessions.Session, rw http.ResponseWriter) (int, string) {
	var id string
	var pass string

	email, password := r.FormValue("email"), r.FormValue("password")
	err := db.QueryRow("select id, password from appuser where email=$1", email).Scan(&id, &pass)

	if err != nil || bcrypt.CompareHashAndPassword([]byte(pass), []byte(password)) != nil {
		//return 401, "Not Authorized. Buuuurn!"
		http.Redirect(rw, r, "/wrong", http.StatusFound)
	}

	//set the user id in the session
	s.Set("userId", id)

	//return user
	if returnUrl, ok := s.Get("returnUrl").(string); ok {
		s.Delete("returnUrl")
		http.Redirect(rw, r, returnUrl, http.StatusFound)
	} else {
		http.Redirect(rw, r, "/", http.StatusFound)
	}

	return 200, "User id is " + id
}

作者:rand9    项目:photoshar   
func (user *User) CheckPassword(password string) bool {
	if user.Password == "" {
		return false
	}
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	return err == nil
}


问题


面经


文章

微信
公众号

扫码关注公众号