Golang GenerateFromPassword示例

说明

golang generatefrompassword示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: golang.org/x/crypto/bcrypt

示例#1
文件: main.go 项目: zykzhang/practice

func tryCrypto() {
	pwd := "pwd"
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	if err != nil {
		P("bcrypt err: ", err)
	}

	P("first, pwd and hansh: \n", pwd, string(hash), len(string(hash)))
	hash2, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	P("second, pwd and hash: \n", pwd, string(hash2), len(string(hash2)))

	P("check pwd..")
	P("check hash1: ")
	err = bcrypt.CompareHashAndPassword(hash, []byte(pwd))
	P(err == nil)
	err = bcrypt.CompareHashAndPassword(hash, []byte("pwds"))
	P(err == nil)
	P("check has2:")
	P("hash1 != hash2: ", string(hash) != string(hash2))
	err = bcrypt.CompareHashAndPassword(hash2, []byte(pwd))
	P(err == nil)
	u := uuid.New()
	P("uuid: ", u, len(u), len(uuid.New()), len(uuid.New()))
	unix := time.Now().Unix()
	unixStr := fmt.Sprintf("%d", unix)
	P("time: ", unix, len(unixStr))

}

示例#2
文件: main.go 项目: RaviTezu/GolangTraining

func main() {
	p := "todd"
	bs, _ := bcrypt.GenerateFromPassword([]byte(p), bcrypt.MinCost)
	fmt.Printf("PASSWORD ONE: %x \n", bs)

	p2 := "todd"
	bs2, _ := bcrypt.GenerateFromPassword([]byte(p2), bcrypt.MinCost)
	fmt.Printf("PASSWORD TWO: %x \n", bs2)
}

示例#3
文件: bcrypt.go 项目: csrgxtu/Gosrc

func main() {
	passwd := "archer"

	crypted, _ := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
	fmt.Println(string(crypted))
	crypteda, _ := bcrypt.GenerateFromPassword([]byte("Archer"), bcrypt.DefaultCost)
	fmt.Println(string(crypteda))
	if err := bcrypt.CompareHashAndPassword(crypted, []byte("Archer")); err != nil {
		fmt.Println("not equal")
	}
}

示例#4
文件: auth.go 项目: johndmulhausen/kubernetes

// merge applies the properties of the passed-in User to the User on which it
// is called and returns a new User with these modifications applied. Think of
// all Users as immutable sets of data. Merge allows you to perform the set
// operations (desired grants and revokes) atomically
func (u User) merge(n User) (User, error) {
	var out User
	if u.User != n.User {
		return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", u.User, n.User)
	}
	out.User = u.User
	if n.Password != "" {
		hash, err := bcrypt.GenerateFromPassword([]byte(n.Password), bcrypt.DefaultCost)
		if err != nil {
			return User{}, err
		}
		out.Password = string(hash)
	} else {
		out.Password = u.Password
	}
	currentRoles := types.NewUnsafeSet(u.Roles...)
	for _, g := range n.Grant {
		if currentRoles.Contains(g) {
			plog.Noticef("granting duplicate role %s for user %s", g, n.User)
			return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, n.User))
		}
		currentRoles.Add(g)
	}
	for _, r := range n.Revoke {
		if !currentRoles.Contains(r) {
			plog.Noticef("revoking ungranted role %s for user %s", r, n.User)
			return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, n.User))
		}
		currentRoles.Remove(r)
	}
	out.Roles = currentRoles.Values()
	sort.Strings(out.Roles)
	return out, nil
}

示例#5
文件: password.go 项目: no2key/dex

func DefaultPasswordHasher(s string) ([]byte, error) {
	pwHash, err := bcrypt.GenerateFromPassword([]byte(s), bcryptHashCost)
	if err != nil {
		return nil, err
	}
	return Password(pwHash), nil
}

示例#6
文件: client.go 项目: aristanetworks/influxdb

func (c *Client) CreateUser(name, password string, admin bool) (*UserInfo, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	data := c.cacheData.Clone()

	// See if the user already exists.
	if u := data.User(name); u != nil {
		if err := bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(password)); err != nil || u.Admin != admin {
			return nil, ErrUserExists
		}
		return u, nil
	}

	// Hash the password before serializing it.
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
	if err != nil {
		return nil, err
	}

	if err := data.CreateUser(name, string(hash), admin); err != nil {
		return nil, err
	}

	u := data.User(name)

	if err := c.commit(data); err != nil {
		return nil, err
	}

	return u, nil
}

示例#7
文件: auth.go 项目: myuchi/myuchi-server

func authGenerate(password string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(hash), nil
}

示例#8
文件: store.go 项目: 40a/bootkube

func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
	plog.Noticef("adding a new user: %s", r.Name)

	hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
	if err != nil {
		plog.Errorf("failed to hash password: %s", err)
		return nil, err
	}

	tx := as.be.BatchTx()
	tx.Lock()
	defer tx.Unlock()

	_, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
	if len(vs) != 0 {
		return &pb.AuthUserAddResponse{}, ErrUserAlreadyExist
	}

	newUser := authpb.User{
		Name:     []byte(r.Name),
		Password: hashed,
	}

	marshaledUser, merr := newUser.Marshal()
	if merr != nil {
		plog.Errorf("failed to marshal a new user data: %s", merr)
		return nil, merr
	}

	tx.UnsafePut(authUsersBucketName, []byte(r.Name), marshaledUser)

	plog.Noticef("added a new user: %s", r.Name)

	return &pb.AuthUserAddResponse{}, nil
}

示例#9
文件: user.go 项目: topher200/forty-thieves

// Signup create a new record of user.
func (u *User) Signup(tx *sqlx.Tx, email, password, passwordAgain string) (*UserRow, error) {
	if email == "" {
		return nil, errors.New("Email cannot be blank.")
	}
	if password == "" {
		return nil, errors.New("Password cannot be blank.")
	}
	if password != passwordAgain {
		return nil, errors.New("Password is invalid.")
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 5)
	if err != nil {
		return nil, err
	}

	data := make(map[string]interface{})
	data["email"] = email
	data["password"] = hashedPassword

	sqlResult, err := u.InsertIntoTable(tx, data)
	if err != nil {
		return nil, err
	}

	return u.userRowFromSqlResult(tx, sqlResult)
}

示例#10
文件: user.go 项目: LukeShu/periwinkle

func (u *User) SetPassword(password string) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), -1)
	if err != nil {
		panic(err) // Luke says this is OK
	}
	u.PwHash = hash
}

示例#11
文件: user.go 项目: Fantasim/Langage-Go

//Hash le password envoyé en parametre et le met dans la variable hashedPassword dans la structure
func (user *User) newCryptPasswd(password []byte) {
	hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	user.hashedPassword = hashedPassword
}

示例#12
文件: formHandles.go 项目: andybenavides/CSCI-191T

func CreateUser(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	ctx := appengine.NewContext(req)

	// Form validation skeleton
	//
	//	var PassVerify = req.FormValue("passWordVerify")
	//	var Password = req.FormValue("passWord")
	//
	//	if(PassVerify != Password){
	//
	//	}

	var password, _ = bcrypt.GenerateFromPassword([]byte(req.FormValue("passWord")), bcrypt.DefaultCost)
	user := User{
		FirstName: req.FormValue("firstName"),
		LastName:  req.FormValue("lastName"),
		UserName:  req.FormValue("userName"),
		Email:     req.FormValue("email"),
		Password:  string(password),
	}

	key := datastore.NewKey(ctx, "Users", user.UserName, 0, nil)
	key, err := datastore.Put(ctx, key, &user)
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	var sd SessionData
	sd.LoggedIn = true

	tpl.ExecuteTemplate(res, "homePage.html", &sd)
}

示例#13
文件: auth.go 项目: topiary-io/topiary

func initAuth() {
	var err error

	// authFile must exist in site home.
	// could intruduce a way to dynamically create one or just default install it
	backend, err = httpauth.NewGobFileAuthBackend(authFile)
	if err != nil {
		panic(err)
	}

	// create some default roles
	roles = make(map[string]httpauth.Role)
	roles["user"] = 30
	roles["admin"] = 80
	aaa, err = httpauth.NewAuthorizer(backend, []byte("cookie-encryption-key"), "user", roles)

	// create a default user
	hash, err := bcrypt.GenerateFromPassword([]byte("adminadmin"), bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	defaultUser := httpauth.UserData{Username: "admin", Email: "[email protected]", Hash: hash, Role: "admin"}
	err = backend.SaveUser(defaultUser)
	if err != nil {
		panic(err)
	}
}

示例#14
文件: user_model.go 项目: niilo/inkblot

//HashPassword takes a plaintext password and hashes it with bcrypt and sets the
//password field to the hash.
func (u *User) HashPassword(password string) {
	hpass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		panic(err) //this is a panic because bcrypt errors on invalid costs
	}
	u.Password = string(hpass)
}

示例#15
文件: hash.go 项目: IIC2173-2015-2-Grupo2/news-api

/*
HashPass apply hashing
*/
func HashPass(pass string) (string, error) {
	if hash, err := bcrypt.GenerateFromPassword([]byte(pass), cost); err != nil {
		return "", err
	} else {
		return string(hash), nil
	}
}

示例#16
文件: auth.go 项目: thansau239/gophish

// Register attempts to register the user given a request.
func Register(r *http.Request) (bool, error) {
	username := r.FormValue("username")
	newPassword := r.FormValue("password")
	confirmPassword := r.FormValue("confirm_password")
	u, err := models.GetUserByUsername(username)
	// If we have an error which is not simply indicating that no user was found, report it
	if err != nil {
		fmt.Println(err)
		return false, err
	}
	u = models.User{}
	// If we've made it here, we should have a valid username given
	// Check that the passsword isn't blank
	if newPassword == "" {
		return false, ErrEmptyPassword
	}
	// Make sure passwords match
	if newPassword != confirmPassword {
		return false, ErrPasswordMismatch
	}
	// Let's create the password hash
	h, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		return false, err
	}
	u.Username = username
	u.Hash = string(h)
	u.ApiKey = GenerateSecureKey()
	err = models.PutUser(&u)
	return true, nil
}

示例#17
文件: user.go 项目: topher200/forty-thieves

// UpdateEmailAndPasswordById updates user email and password.
func (u *User) UpdateEmailAndPasswordById(tx *sqlx.Tx, userId int64, email, password, passwordAgain string) (*UserRow, error) {
	data := make(map[string]interface{})

	if email != "" {
		data["email"] = email
	}

	if password != "" && passwordAgain != "" && password == passwordAgain {
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 5)
		if err != nil {
			return nil, err
		}

		data["password"] = hashedPassword
	}

	if len(data) > 0 {
		_, err := u.UpdateById(tx, data, userId)
		if err != nil {
			return nil, err
		}
	}

	return u.GetById(tx, userId)
}

示例#18
文件: db.go 项目: hheld/UserAdminWebApp

func updateUserPwdInDb(userId, newPwd, currentPwd string) error {
	if dbCollection == nil {
		return errors.New("There is no connection to a database!")
	}

	result := User{}
	err := dbCollection.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(&result)

	if err != nil {
		return err
	}

	_, err = validateUserInDb(result.UserName, currentPwd)

	if err != nil {
		return err
	}

	hashedPwd, err := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)

	if err != nil {
		return err
	}

	return dbCollection.Update(bson.M{"_id": bson.ObjectIdHex(userId)}, bson.M{"$set": bson.M{
		"passwordhash": hashedPwd,
	}})
}

示例#19
文件: store.go 项目: 40a/bootkube

func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
	// TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
	// If the cost is too high, we should move the encryption to outside of the raft
	hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
	if err != nil {
		plog.Errorf("failed to hash password: %s", err)
		return nil, err
	}

	tx := as.be.BatchTx()
	tx.Lock()
	defer tx.Unlock()

	_, vs := tx.UnsafeRange(authUsersBucketName, []byte(r.Name), nil, 0)
	if len(vs) != 1 {
		return &pb.AuthUserChangePasswordResponse{}, ErrUserNotFound
	}

	updatedUser := authpb.User{
		Name:     []byte(r.Name),
		Password: hashed,
	}

	marshaledUser, merr := updatedUser.Marshal()
	if merr != nil {
		plog.Errorf("failed to marshal a new user data: %s", merr)
		return nil, merr
	}

	tx.UnsafePut(authUsersBucketName, []byte(r.Name), marshaledUser)

	plog.Noticef("changed a password of a user: %s", r.Name)

	return &pb.AuthUserChangePasswordResponse{}, nil
}

示例#20
文件: store.go 项目: ASAPPinc/influxdb

// NewStore returns a new instance of Store.
func NewStore(c *Config) *Store {
	s := &Store{
		path:  c.Dir,
		peers: c.Peers,
		join:  c.Join,
		data:  &Data{},

		ready:   make(chan struct{}),
		err:     make(chan error),
		closing: make(chan struct{}),
		changed: make(chan struct{}),

		clusterTracingEnabled: c.ClusterTracing,
		retentionAutoCreate:   c.RetentionAutoCreate,

		HeartbeatTimeout:   time.Duration(c.HeartbeatTimeout),
		ElectionTimeout:    time.Duration(c.ElectionTimeout),
		LeaderLeaseTimeout: time.Duration(c.LeaderLeaseTimeout),
		CommitTimeout:      time.Duration(c.CommitTimeout),
		authCache:          make(map[string]authUser, 0),
		hashPassword: func(password string) ([]byte, error) {
			return bcrypt.GenerateFromPassword([]byte(password), BcryptCost)
		},
		Logger: log.New(os.Stderr, "[metastore] ", log.LstdFlags),
	}

	s.raftState = &localRaft{store: s}
	s.rpc = &rpc{
		store:          s,
		tracingEnabled: c.ClusterTracing,
		logger:         s.Logger,
	}
	return s
}

示例#21
文件: addparent.go 项目: jefflub/allowance

// AddParent adds a parent. Uses passed transaction or a new one if one is not provided
func AddParent(familyID int, name string, email string, password string, tx *sql.Tx) (int, error) {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	needCommit := false
	if tx == nil {
		tx, err = db.Begin()
		if err != nil {
			return 0, err
		}
		needCommit = true
		defer tx.Rollback()
	}

	// Create the parent
	if _, err := tx.Exec("INSERT INTO parents VALUES(NULL, ?, ?, ?, ?, NULL, NULL)", familyID, name, email, hashedPassword); err != nil {
		return 0, err
	}
	// Get the ID
	var ID int
	row := tx.QueryRow("SELECT LAST_INSERT_ID()")
	err = row.Scan(&ID)
	if needCommit {
		tx.Commit()
	}

	return ID, err
}

示例#22
文件: store.go 项目: luizbafilho/fusis

func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
	if len(r.Name) == 0 {
		return nil, ErrUserEmpty
	}

	hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
	if err != nil {
		plog.Errorf("failed to hash password: %s", err)
		return nil, err
	}

	tx := as.be.BatchTx()
	tx.Lock()
	defer tx.Unlock()

	user := getUser(tx, r.Name)
	if user != nil {
		return nil, ErrUserAlreadyExist
	}

	newUser := &authpb.User{
		Name:     []byte(r.Name),
		Password: hashed,
	}

	putUser(tx, newUser)

	as.commitRevision(tx)

	plog.Noticef("added a new user: %s", r.Name)

	return &pb.AuthUserAddResponse{}, nil
}

示例#23
文件: testdata.go 项目: jtprog/geotrack

// GetSampleGroupID возвращает тестовый предопределенный идентификатор группы.
func (db *DB) GetSampleGroupID() string {
	group, err := db.GetGroup(SampleGroupID)
	if err != nil {
		panic(err)
	}
	// наполняем тестовыми данными
	if group == nil {
		for i := 0; i < 5; i++ {
			password, err := bcrypt.GenerateFromPassword(
				[]byte(fmt.Sprintf("password%d", i+1)), bcrypt.DefaultCost)
			if err != nil {
				panic(err)
			}
			err = db.Save(&User{
				Login:    fmt.Sprintf("login%d", i+1),
				GroupID:  SampleGroupID,
				Name:     fmt.Sprintf("User #%d", i+1),
				Icon:     byte(i),
				Password: password,
			})
			if err != nil {
				panic(err)
			}
		}
	}
	return SampleGroupID
}

示例#24
文件: store.go 项目: luizbafilho/fusis

func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
	// TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
	// If the cost is too high, we should move the encryption to outside of the raft
	hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
	if err != nil {
		plog.Errorf("failed to hash password: %s", err)
		return nil, err
	}

	tx := as.be.BatchTx()
	tx.Lock()
	defer tx.Unlock()

	user := getUser(tx, r.Name)
	if user == nil {
		return nil, ErrUserNotFound
	}

	updatedUser := &authpb.User{
		Name:     []byte(r.Name),
		Roles:    user.Roles,
		Password: hashed,
	}

	putUser(tx, updatedUser)

	as.commitRevision(tx)

	as.invalidateCachedPerm(r.Name)
	as.invalidateUser(r.Name)

	plog.Noticef("changed a password of a user: %s", r.Name)

	return &pb.AuthUserChangePasswordResponse{}, nil
}

示例#25
文件: api.go 项目: RaviTezu/GolangTraining

func createUser(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	ctx := appengine.NewContext(req)
	hashedPass, err := bcrypt.GenerateFromPassword([]byte(req.FormValue("password")), bcrypt.DefaultCost)
	if err != nil {
		log.Errorf(ctx, "error creating password: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}
	user := User{
		Email:    req.FormValue("email"),
		UserName: req.FormValue("userName"),
		Password: string(hashedPass),
	}
	key := datastore.NewKey(ctx, "Users", user.UserName, 0, nil)
	key, err = datastore.Put(ctx, key, &user)
	if err != nil {
		log.Errorf(ctx, "error adding todo: %v", err)
		http.Error(res, err.Error(), 500)
		return
	}

	createSession(res, req, user)
	// redirect
	http.Redirect(res, req, "/", 302)
}

示例#26
文件: postmapweb.go 项目: fazalmajid/postmapweb

func updateConf(conf Config, conf_file string, domain string, virtual string, password []byte) {
	pass_hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		log.Fatal("Could not hash the password: ", err)
	}
	// if the domain already exists in the config file,
	// change the password and map file
	existing := false
	for i, d := range conf.Domains {
		if d.Name == domain {
			existing = true
			conf.Domains[i].MapFile = virtual
			conf.Domains[i].PassHash = string(pass_hash)
		}
	}
	if !existing {
		conf.Domains = append(conf.Domains, Domain{domain, virtual, string(pass_hash)})
	}
	conf_json, err := json.MarshalIndent(conf, "", "  ")
	if err != nil {
		log.Fatal("Could not marshal the config: ", err)
	}
	f, err := os.OpenFile(conf_file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		log.Fatal("could not write conf file ", conf_file, " due to ", err)
	}
	nbytes, err := f.Write(conf_json)
	if err != nil || nbytes < len(conf_json) {
		log.Fatal("could not write conf file ", conf_file, " due to ", err)
	}
	err = f.Close()
	if err != nil {
		log.Fatal("could not finish writing conf file ", conf_file, " due to ", err)
	}
}

示例#27
文件: password.go 项目: phuc0302/go-oauth2

// EncryptPassword will cipher user's password using bcrypt.
func EncryptPassword(password string) (string, error) {
	password = strings.Trim(password, " ")
	input := []byte(password)

	hash, err := bcrypt.GenerateFromPassword(input, bcrypt.DefaultCost)
	return string(hash), err
}

示例#28
文件: stores.go 项目: Trainning-GPAT-Sep2015/Exercise

func HashPassword(password string) string {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)
	if err != nil {
		panic(err)
	}
	return string(hashedPassword)
}

示例#29
文件: password.go 项目: sshitaime/journey

func EncryptPassword(password string) (string, error) {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)
	if err != nil {
		return "", err
	}
	return string(hashedPassword), nil
}

示例#30
文件: auth.go 项目: thansau239/gophish

func ChangePassword(r *http.Request) error {
	u := ctx.Get(r, "user").(models.User)
	currentPw := r.FormValue("current_password")
	newPassword := r.FormValue("new_password")
	confirmPassword := r.FormValue("confirm_new_password")
	// Check the current password
	err := bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(currentPw))
	if err != nil {
		return ErrInvalidPassword
	}
	// Check that the new password isn't blank
	if newPassword == "" {
		return ErrEmptyPassword
	}
	// Check that new passwords match
	if newPassword != confirmPassword {
		return ErrPasswordMismatch
	}
	// Generate the new hash
	h, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Hash = string(h)
	if err = models.PutUser(&u); err != nil {
		return err
	}
	return nil
}

展开阅读全文