当前位置: 首页>>代码示例>>Golang>>正文


Golang bcrypt.CompareHashAndPassword函数代码示例

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


在下文中一共展示了CompareHashAndPassword函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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() {
	s := "Password"
	p, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(bcrypt.CompareHashAndPassword(p, []byte("Password")))
	fmt.Println(bcrypt.CompareHashAndPassword(p, []byte("Passwordadfadf")))
	fmt.Println(bcrypt.ErrMismatchedHashAndPassword)
}
开发者ID:Saxleader,项目名称:fall2015,代码行数:10,代码来源:Test.go

示例3: BasicAuth

func BasicAuth(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("WWW-Authenicate", `Basic realm="Restricted`)
		s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
		if len(s) != 2 {
			log.Warn(r.RemoteAddr, "auth Error")
			http.Error(w, "Not authorized", 401)
			return
		}

		b, err := base64.StdEncoding.DecodeString(s[1])
		if err != nil {
			http.Error(w, err.Error(), 401)
			return
		}
		pair := strings.SplitN(string(b), ":", 2)
		if len(pair) != 2 {
			log.Warn(r.RemoteAddr, " auth param empty")
			http.Error(w, "Not authorized", 401)
			return
		}

		params := mux.Vars(r)
		var account string
		var password string

		//super admin 可通過任何api
		if pair[0] == GlobalConf.AuthAccount && bcrypt.CompareHashAndPassword([]byte(GlobalConf.AuthPassword), []byte(pair[0]+pair[1])) == nil {
			h.ServeHTTP(w, r)
			return
		}

		if params["app_key"] != "" {
			data, err := Model.Get(params["app_key"])
			if err != nil {
				log.Warn(r.RemoteAddr, " ", err.Error())
				http.Error(w, err.Error(), 401)
				return
			}
			account = data.AuthAccount
			password = data.AuthPassword
		}

		if pair[0] != account || bcrypt.CompareHashAndPassword([]byte(password), []byte(pair[0]+pair[1])) != nil {
			log.Warn(r.RemoteAddr, " auth error "+pair[0]+" "+pair[1])
			http.Error(w, "Not authorized", 401)
			return
		}
		h.ServeHTTP(w, r)

	}
}
开发者ID:syhlion,项目名称:gusher,代码行数:52,代码来源:middleware.go

示例4: authUser

// Authenticate User
func authUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	buf := new(bytes.Buffer)
	auth := &struct {
		UserHandle string
		Password   string
	}{}
	buf.ReadFrom(r.Body)
	err := json.Unmarshal(buf.Bytes(), auth)
	if err != nil {
		writeJsonERR(w, 400, "Invalid JSON!")
		return
	}
	var passBuf []byte
	var id int
	err = db.QueryRow(`Select passwordbcrypt, id from users where email = $1 or handle = $1`, auth.UserHandle).Scan(&passBuf, &id)
	if err == sql.ErrNoRows {
		err = bcrypt.CompareHashAndPassword(passBuf, []byte(auth.Password))
		writeJsonERR(w, 400, "User name or password not found")
		return
	}
	if err != nil {
		fmt.Println(err)
		writeJsonERR(w, 500, "Server error!")
		return
	}
	err = bcrypt.CompareHashAndPassword(passBuf, []byte(auth.Password))
	if err != nil {
		writeJsonERR(w, 400, "User name or password not found")
		return
	}

	sessionKey, err1 := GetSessionKey(id)
	userAuth := &struct {
		Error     string
		UserID    int
		SessionID string
	}{"", id, sessionKey}

	if err1 != nil {
		panic(err1)
	}

	data, err := json.Marshal(userAuth)
	if err != nil {
		panic(err)
	}
	w.Write(data)
}
开发者ID:5-Bit,项目名称:eagleslist-server,代码行数:49,代码来源:api.go

示例5: ValidatePassword

func (u *BaseUser) ValidatePassword(password string) (bool, error) {
	if err := bcrypt.CompareHashAndPassword(u.passHash, []byte(password)); err != nil {
		return false, err
	}
	return true, nil

}
开发者ID:archeious,项目名称:ARES,代码行数:7,代码来源:baseUser.go

示例6: ValidatePassword

func ValidatePassword(pwh, pw []byte) bool {
	err := bcrypt.CompareHashAndPassword(pwh, pw)
	if err != nil {
		return false
	}
	return true
}
开发者ID:johnwilson,项目名称:bytengine,代码行数:7,代码来源:utils.go

示例7: VerifyPassword

// VerifyPassword compare a field of an item payload containig a hashed password
// with a clear text password and return true if they match.
func VerifyPassword(hash interface{}, password []byte) bool {
	h, ok := hash.([]byte)
	if !ok {
		return false
	}
	return bcrypt.CompareHashAndPassword(h, password) == nil
}
开发者ID:rs,项目名称:rest-layer,代码行数:9,代码来源:password.go

示例8: authCompare

func authCompare(password, hash string) error {
	hashed, err := base64.StdEncoding.DecodeString(hash)
	if err != nil {
		return err
	}
	return bcrypt.CompareHashAndPassword(hashed, []byte(password))
}
开发者ID:myuchi,项目名称:myuchi-server,代码行数:7,代码来源:auth.go

示例9: ValidatePassword

func (u *User) ValidatePassword(password string) bool {
	e := bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(password))
	if e != nil {
		return false
	}
	return true
}
开发者ID:zhuharev,项目名称:users,代码行数:7,代码来源:users.go

示例10: ChangePassword

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

示例11: Authenticate

func (BasicAuth) Authenticate(secret string) (types.Uid, time.Time, int) {
	uname, password, fail := parseSecret(secret)
	if fail != auth.NoErr {
		return types.ZeroUid, time.Time{}, fail
	}

	uid, passhash, expires, err := store.Users.GetAuthRecord("basic", uname)
	if err != nil {
		log.Println(err)
		return types.ZeroUid, time.Time{}, auth.ErrInternal
	} else if uid.IsZero() {
		// Invalid login.
		return types.ZeroUid, time.Time{}, auth.ErrFailed
	} else if !expires.IsZero() && expires.Before(time.Now()) {
		// The record has expired
		return types.ZeroUid, time.Time{}, auth.ErrExpired
	}

	err = bcrypt.CompareHashAndPassword([]byte(passhash), []byte(password))
	if err != nil {
		log.Println(err)
		// Invalid password
		return types.ZeroUid, time.Time{}, auth.ErrFailed
	}

	return uid, expires, auth.NoErr

}
开发者ID:ycaihua,项目名称:chat,代码行数:28,代码来源:auth_basic.go

示例12: Authenticate

// Authenticate tries to authenticate a given username/password combination
// against the database. It is guaranteed to take at least 200 Milliseconds. It
// returns ErrWrongAuth, if the user or password was wrong. If no error
// occured, it will return a fully populated User.
func (k *Kasse) Authenticate(username string, password []byte) (*User, error) {
	k.log.Printf("Verifying user %v", username)
	delay := time.After(200 * time.Millisecond)
	defer func() {
		<-delay
	}()

	user := new(User)
	if err := k.db.Get(user, `SELECT user_id, name, password FROM users WHERE name = $1`, username); err == sql.ErrNoRows {
		k.log.Printf("No such user %v", username)
		return nil, ErrWrongAuth
	} else if err != nil {
		return nil, err
	}

	if err := bcrypt.CompareHashAndPassword(user.Password, password); err == bcrypt.ErrMismatchedHashAndPassword {
		k.log.Println("Wrong password")
		return nil, ErrWrongAuth
	} else if err != nil {
		return nil, err
	}

	k.log.Printf("Successfully authenticated %v", username)
	return user, nil
}
开发者ID:tynsh,项目名称:kasse,代码行数:29,代码来源:main.go

示例13: NewBasic

// NewBasic returns a negroni.HandlerFunc that authenticates via Basic auth using data store.
// Writes a http.StatusUnauthorized if authentication fails.
func NewBasic(datastore datastore.Datastore) negroni.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
		// Extract userid, password from request.
		userId, password := getCred(req)

		if userId == "" {
			requireAuth(w)
			return
		}

		// Extract hashed passwor from credentials.
		hashedPassword, found := datastore.Get(userId)
		if !found {
			requireAuth(w)
			return
		}

		// Check if the password is correct.
		err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
		// Password not correct. Fail.
		if err != nil {
			requireAuth(w)
			return
		}

		r := w.(negroni.ResponseWriter)

		// Password correct.
		if r.Status() != http.StatusUnauthorized {
			next(w, req)
		}
	}
}
开发者ID:nabeken,项目名称:negroni-auth,代码行数:35,代码来源:basic.go

示例14: comparePasswordHash

func comparePasswordHash(passHash, plainpassword string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(passHash), []byte(plainpassword))
	if err != nil {
		return false
	}
	return true
}
开发者ID:suricatatalk,项目名称:guardian,代码行数:7,代码来源:provider.go

示例15: CompareHash

// CompareHash compares bcrypt password with a plaintext one. Returns true if passwords match
// and false if they do not.
func CompareHash(digest []byte, password string) bool {
	hex := []byte(password)
	if err := bcrypt.CompareHashAndPassword(digest, hex); err == nil {
		return true
	}
	return false
}
开发者ID:jayrox,项目名称:Vertigo-alice,代码行数:9,代码来源:crypto.go


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