• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang bcrypt.GenerateFromPassword函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中golang.org/x/crypto/bcrypt.GenerateFromPassword函数的典型用法代码示例。如果您正苦于以下问题:Golang GenerateFromPassword函数的具体用法?Golang GenerateFromPassword怎么用?Golang GenerateFromPassword使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GenerateFromPassword函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: tryCrypto

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))

}
开发者ID:zykzhang,项目名称:practice,代码行数:28,代码来源:main.go


示例2: main

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)
}
开发者ID:RaviTezu,项目名称:GolangTraining,代码行数:9,代码来源:main.go


示例3: main

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")
	}
}
开发者ID:csrgxtu,项目名称:Gosrc,代码行数:11,代码来源:bcrypt.go


示例4: merge

// 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
}
开发者ID:johndmulhausen,项目名称:kubernetes,代码行数:38,代码来源:auth.go


示例5: DefaultPasswordHasher

func DefaultPasswordHasher(s string) ([]byte, error) {
	pwHash, err := bcrypt.GenerateFromPassword([]byte(s), bcryptHashCost)
	if err != nil {
		return nil, err
	}
	return Password(pwHash), nil
}
开发者ID:no2key,项目名称:dex,代码行数:7,代码来源:password.go


示例6: CreateUser

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
}
开发者ID:aristanetworks,项目名称:influxdb,代码行数:32,代码来源:client.go


示例7: authGenerate

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
}
开发者ID:myuchi,项目名称:myuchi-server,代码行数:7,代码来源:auth.go


示例8: UserAdd

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
}
开发者ID:40a,项目名称:bootkube,代码行数:35,代码来源:store.go


示例9: Signup

// 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)
}
开发者ID:topher200,项目名称:forty-thieves,代码行数:28,代码来源:user.go


示例10: SetPassword

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
}
开发者ID:LukeShu,项目名称:periwinkle,代码行数:7,代码来源:user.go


示例11: newCryptPasswd

//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
}
开发者ID:Fantasim,项目名称:Langage-Go,代码行数:8,代码来源:user.go


示例12: CreateUser

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)
}
开发者ID:andybenavides,项目名称:CSCI-191T,代码行数:33,代码来源:formHandles.go


示例13: initAuth

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)
	}
}
开发者ID:topiary-io,项目名称:topiary,代码行数:27,代码来源:auth.go


示例14: HashPassword

//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)
}
开发者ID:niilo,项目名称:inkblot,代码行数:9,代码来源:user_model.go


示例15: HashPass

/*
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
	}
}
开发者ID:IIC2173-2015-2-Grupo2,项目名称:news-api,代码行数:10,代码来源:hash.go


示例16: Register

// 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
}
开发者ID:thansau239,项目名称:gophish,代码行数:32,代码来源:auth.go


示例17: UpdateEmailAndPasswordById

// 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)
}
开发者ID:topher200,项目名称:forty-thieves,代码行数:26,代码来源:user.go


示例18: updateUserPwdInDb

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,
	}})
}
开发者ID:hheld,项目名称:UserAdminWebApp,代码行数:28,代码来源:db.go


示例19: UserChangePassword

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
}
开发者ID:40a,项目名称:bootkube,代码行数:35,代码来源:store.go


示例20: NewStore

// 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
}
开发者ID:ASAPPinc,项目名称:influxdb,代码行数:35,代码来源:store.go



注:本文中的golang.org/x/crypto/bcrypt.GenerateFromPassword函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang curve25519.ScalarBaseMult函数代码示例发布时间:2022-05-28
下一篇:
Golang bcrypt.CompareHashAndPassword函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap