package crypto import ( "golang.org/x/crypto/bcrypt" ) // PasswordHash 使用bcrypt对密码进行加密 // cost参数确定加密的复杂度,默认为10,越高越安全但性能消耗越大 func PasswordHash(password string, cost ...int) (string, error) { defaultCost := 10 if len(cost) > 0 && cost[0] > 0 { defaultCost = cost[0] } bytes, err := bcrypt.GenerateFromPassword([]byte(password), defaultCost) if err != nil { return "", err } return string(bytes), nil } // PasswordVerify 验证密码是否匹配 // password是用户输入的明文密码,hash是存储的加密密码 func PasswordVerify(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil }