本文整理汇总了Golang中golang.org/x/crypto/bcrypt.CompareHashAndPassword函数的典型用法代码示例。如果您正苦于以下问题:Golang CompareHashAndPassword函数的具体用法?Golang CompareHashAndPassword怎么用?Golang CompareHashAndPassword使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CompareHashAndPassword函数的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() {
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
示例16: signinHandler
func signinHandler(w http.ResponseWriter, r *http.Request) {
var dbpassword []byte
valid := false
username := r.FormValue("suUsername")
password := r.FormValue("suPassword")
signinPassword := []byte(password)
rows, err := db.Query("select username, password from users where username = $1;", username)
util.CheckErr(err)
log.Println(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&username, &dbpassword)
util.CheckErr(err)
log.Println(username)
log.Println(dbpassword)
log.Println(signinPassword)
util.CheckErr(bcrypt.CompareHashAndPassword(dbpassword, signinPassword)) //if no message about nonmatch, successful login verification achieved
//util.CheckErr(bcrypt.CompareHashAndPassword(dbpassword, hashedSigninPassword))
if err == nil {
valid = true
}
}
err = rows.Err()
util.CheckErr(err)
fmt.Println(valid)
if valid == true {
http.Redirect(w, r, "http://localhost:8080/homepage/v.html", 302)
}
}
开发者ID:Doozleberry,项目名称:tutoring-website,代码行数:29,代码来源:handlers.go
示例17: SignInPost
//SignInPost handles POST /signin route, authenticates user
func SignInPost(c *gin.Context) {
session := sessions.Default(c)
user := &models.User{}
if err := c.Bind(user); err != nil {
session.AddFlash("Please, fill out form correctly.")
session.Save()
c.Redirect(http.StatusFound, "/signin")
return
}
userDB, _ := models.GetUserByEmail(user.Email)
if userDB.ID == 0 {
logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
session.AddFlash("Email or password incorrect")
session.Save()
c.Redirect(http.StatusFound, "/signin")
return
}
if err := bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password)); err != nil {
logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
session.AddFlash("Email or password incorrect")
session.Save()
c.Redirect(http.StatusFound, "/signin")
return
}
session.Set("UserID", userDB.ID)
session.Save()
c.Redirect(http.StatusFound, "/")
}
开发者ID:denisbakhtin,项目名称:ginblog,代码行数:31,代码来源:auth.go
示例18: loginUser
func loginUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
var u bson.M
if err := r.DecodeJsonPayload(&u); err != nil {
RestError(w, err)
return
}
existingUser, err := db.FindId(u["email"].(string), nil)
if err != nil {
RestError(w, err)
return
}
err = bcrypt.CompareHashAndPassword(existingUser["password"].([]byte), []byte(u["password"].(string)))
if err != nil {
RestError(w, err)
return
}
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["user"] = u["email"].(string)
token.Claims["expiration"] = time.Now().Add(time.Minute + 60).Unix()
tokenStr, err := token.SignedString([]byte(""))
if err != nil {
RestError(w, err)
return
}
w.WriteJson(map[string]string{"token": tokenStr})
}
开发者ID:gitter-badger,项目名称:neutrino-core,代码行数:35,代码来源:auth.go
示例19: BasicAuth
func BasicAuth() echo.HandlerFunc {
return func(c *echo.Context) error {
// Skip WebSocket
if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
return nil
}
auth := c.Request().Header.Get(echo.Authorization)
l := len(Basic)
if len(auth) > l+1 && auth[:l] == Basic {
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
if err == nil {
cred := string(b)
for i := 0; i < len(cred); i++ {
if cred[i] == ':' {
// Verify credentials
for _, d := range conf.Domains {
if cred[:i] == d.Name && bcrypt.CompareHashAndPassword([]byte(d.PassHash), []byte(cred[i+1:])) == nil {
c.Set("domain", d)
return nil
}
}
}
}
}
}
c.Response().Header().Set(echo.WWWAuthenticate, Basic+" realm=Restricted")
return echo.NewHTTPError(http.StatusUnauthorized)
}
}
开发者ID:fazalmajid,项目名称:postmapweb,代码行数:31,代码来源:postmapweb.go
示例20: Login
// Login logs a user in. They will be redirected to dest or to the last
// location an authorization redirect was triggered (if found) on success. A
// message will be added to the session on failure with the reason.
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
session, _ := a.cookiejar.Get(req, "auth")
if session.Values["username"] != nil {
return mkerror("already authenticated")
}
if user, err := a.backend.User(u); err == nil {
verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))
if verify != nil {
a.addMessage(rw, req, "Invalid username or password.")
return mkerror("password doesn't match")
}
} else {
a.addMessage(rw, req, "Invalid username or password.")
return mkerror("user not found")
}
session.Values["username"] = u
session.Save(req, rw)
redirectSession, _ := a.cookiejar.Get(req, "redirects")
if flashes := redirectSession.Flashes(); len(flashes) > 0 {
dest = flashes[0].(string)
}
http.Redirect(rw, req, dest, http.StatusSeeOther)
return nil
}
开发者ID:singnurkar,项目名称:httpauth,代码行数:28,代码来源:auth.go
注:本文中的golang.org/x/crypto/bcrypt.CompareHashAndPassword函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论