當前位置: 首頁>>代碼示例>>Golang>>正文


Golang bcrypt.GenerateFromPassword函數代碼示例

本文整理匯總了Golang中code/google/com/p/go/crypto/bcrypt.GenerateFromPassword函數的典型用法代碼示例。如果您正苦於以下問題:Golang GenerateFromPassword函數的具體用法?Golang GenerateFromPassword怎麽用?Golang GenerateFromPassword使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了GenerateFromPassword函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: GenerateSecret

func (user *User) GenerateSecret() string {
	base := make([]byte, 256)
	for i, _ := range base {
		base[i] = byte(rand.Int())
	}

	bytes, err := bcrypt.GenerateFromPassword([]byte(base), bcrypt.MinCost)
	if err != nil {
		fmt.Println("Error generating secret hash:", err)
		return ""
	}
	secret := string(bytes)
	// secret = secret[7:]
	fmt.Println("Generate secret:", secret)

	hash, err := bcrypt.GenerateFromPassword([]byte(secret), 12)
	if err != nil {
		fmt.Println("Error generating secret hash:", err)
	}
	fmt.Println("Generate secret: hash:", string(hash))
	user.Secret = string(hash)
	user.Save()

	return secret
}
開發者ID:knight73geo,項目名稱:charactersheets,代碼行數:25,代碼來源:model.go

示例2: Set

// Set associates the plain text password given with the user that is uniquely
// identified by id. The password is hashed with bcrypt. If there is a problem
// with hashing or with storing the password, an error is returned.
//
// This may be called on a new user.
func (s *Store) Set(id, password string) (cerr error) {
	defer csql.Safe(&cerr)

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

	// This lock can be avoided if we use some sort of upsert.
	// It's possible with Postgres, but this is just way easier.
	locker.Lock(id)
	defer locker.Unlock(id)

	n := csql.Count(s, `
		SELECT COUNT(*) FROM `+SqlTableName+` WHERE id = $1
		`, id)
	if n == 0 {
		csql.Exec(s, `
			INSERT INTO `+SqlTableName+` (id, hash) VALUES ($1, $2)
			`, id, hash)
	} else {
		csql.Exec(s, `
			UPDATE `+SqlTableName+` SET id = $1, hash = $2 WHERE id = $1
			`, id, hash)
	}
	return nil
}
開發者ID:BurntSushi,項目名稱:sqlauth,代碼行數:33,代碼來源:store.go

示例3: TestUserCheckPasswordChecksBcryptPasswordFirst

func (s *S) TestUserCheckPasswordChecksBcryptPasswordFirst(c *gocheck.C) {
	passwd, err := bcrypt.GenerateFromPassword([]byte("123456"), cost)
	c.Assert(err, gocheck.IsNil)
	u := User{Email: "[email protected]", Password: string(passwd)}
	err = u.CheckPassword("123456")
	c.Assert(err, gocheck.IsNil)
}
開發者ID:rpeterson,項目名稱:tsuru,代碼行數:7,代碼來源:user_test.go

示例4: hashPassword

// Encrypts the user password before saving it in the database.
func (user *User) hashPassword() {
	if hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost); err == nil {
		user.Password = string(hash[:])
	} else {
		Logger.Error(err.Error())
	}
}
開發者ID:yonglehou,項目名稱:maestro,代碼行數:8,代碼來源:user.go

示例5: GorpInit

func GorpInit() {
	db.Init()
	Dbm = &gorp.DbMap{Db: db.Db, Dialect: gorp.PostgresDialect{}}

	ub := Dbm.AddTable(models.UserBase{}).SetKeys(true, "UserId")
	ub.ColMap("Email").Unique = true
	setColumnSizes(ub, map[string]int{
		"UserName": 32,
		"Email":    64,
	})

	Dbm.AddTable(models.UserVolatile{}).SetKeys(true, "UserId")
	Dbm.AddTable(models.UserAuth{}).SetKeys(true, "UserId")

	Dbm.TraceOn("[gorp]", log.New(GLogger{glog.Info}, "", 0))
	Dbm.CreateTablesIfNotExists()

	if fill {
		now := time.Now().UnixNano()

		demoUser := &models.UserBase{0, "demo", "[email protected]"}
		errU := Dbm.Insert(demoUser)
		checkFail(errU)

		demoVolatile := &models.UserVolatile{demoUser.UserId, now, 0, 0, 0, now}
		errV := Dbm.Insert(demoVolatile)
		checkFail(errV)

		demoPassword, _ := bcrypt.GenerateFromPassword([]byte("demo"), bcrypt.DefaultCost)
		demoAuth := &models.UserAuth{demoUser.UserId, demoPassword, "", 0, 0, 0, 0}
		errA := Dbm.Insert(demoAuth)
		checkFail(errA)
	}

}
開發者ID:kcolls,項目名稱:revel-modz,代碼行數:35,代碼來源:gorp.go

示例6: Init

func Init() {
	db.Init()
	Dbm = &gorp.DbMap{Db: db.Db, Dialect: gorp.SqliteDialect{}}

	setColumnSizes := func(t *gorp.TableMap, colSizes map[string]int) {
		for col, size := range colSizes {
			t.ColMap(col).MaxSize = size
		}
	}

	t := Dbm.AddTable(models.User{}).SetKeys(true, "UserId")
	t.ColMap("Password").Transient = true
	setColumnSizes(t, map[string]int{
		"Username": 20,
		"Name":     100,
	})

	t = Dbm.AddTable(models.Post{}).SetKeys(true, "PostId")
	setColumnSizes(t, map[string]int{
		"Body": 100,
	})

	Dbm.TraceOn("[gorp]", r.INFO)
	Dbm.CreateTables()

	//	setting admin password
	bcryptPassword, _ := bcrypt.GenerateFromPassword(
		[]byte("demo"), bcrypt.DefaultCost)
	demoUser := &models.User{0, "Demo User", "demo", "demo", bcryptPassword}
	if err := Dbm.Insert(demoUser); err != nil {
		panic(err)
	}
}
開發者ID:jhotta,項目名稱:revelFramework4Go,代碼行數:33,代碼來源:gorp.go

示例7: authHassPassword

//hash user password
func authHassPassword(password string) (string, error) {
	bytePass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", nil
	}
	return string(bytePass), nil
}
開發者ID:JohnTroony,項目名稱:ircboks,代碼行數:8,代碼來源:user.go

示例8: AddClient

// AddClient creates the named client tunnel configuration.
func AddClient(
	name, hostAddr, connectAddr string, localPort int32) (err error) {

	// Create the client's tunnel configuration.
	tc := TunnelConfig{}
	tc.Host = hostAddr
	tc.Pwd = make([]byte, 48)
	tc.Port = localPort

	if _, err = rand.Read(tc.Pwd); err != nil {
		return
	}

	_, tc.CaCert, err = loadKeyAndCert()
	if err != nil {
		return
	}

	// Create the server's configuration file.
	cc := ClientConfig{}
	cc.ConnectAddr = connectAddr
	cc.PwdHash, err = bcrypt.GenerateFromPassword(tc.Pwd, bcrypt.DefaultCost)
	if err != nil {
		return
	}

	// Write the config files.
	if err = tc.Save(clientTunnelPath(name)); err != nil {
		return
	}

	err = cc.Save(clientsPath(name))

	return
}
開發者ID:pombredanne,項目名稱:ttunnel,代碼行數:36,代碼來源:addclient.go

示例9: BcryptHash

// BcryptHash returns the bcrypt hash of the password at the default cost.
// Panics on error. Result is byte array. Based on bcrypt.GenerateFromPassword
func BcryptHash(password []byte) []byte {
	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	return hash
}
開發者ID:vgorin,項目名稱:cryptogo,代碼行數:9,代碼來源:hash.go

示例10: NewUser

func NewUser(email string, password string) *User {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)
	if err != nil {
		return nil
	}
	return &User{email, hashedPassword}
}
開發者ID:jroes,項目名稱:gorum,代碼行數:7,代碼來源:user.go

示例11: GenerateBcryptHash

// Generate a bcrypt hash given a request.
func GenerateBcryptHash(hr *HashRequest) (*HashResponse, error) {

	// First, grab the hash options and either use what the user specified or
	// set them to the defaults (recommended).
	if err := mergo.Merge(hr.Options, DefaultHashRequestOptions); err != nil {
		return nil, errors.New("Invalid options specified.")
	}

	// If the user specified no cost (or a cost smaller than the minimum
	// allowed), we'll automatically set the cost to the bcrypt library's
	// recommended value.
	if hr.Options.Cost < bcrypt.MinCost {
		hr.Options.Cost = bcrypt.DefaultCost
	}

	// Compute the bcrypt hash.
	hash, err := bcrypt.GenerateFromPassword([]byte(hr.String), hr.Options.Cost)
	if err != nil {
		return nil, errors.New("Could not compute the bcrypt hash.")
	}

	// Send our response to the user.
	return &HashResponse{Hash: string(hash)}, nil

}
開發者ID:rdegges,項目名稱:cryptly-api,代碼行數:26,代碼來源:cryptly.go

示例12: SetPassword

func (u *user) SetPassword(password string) {
	hpass, err := bcrypt.GenerateFromPassword([]byet(password), bcrypt.DefaultCost)
	if err != nil {
		panic(err) //this is a panic because bcrypt errors on invalid cost
	}
	u.Password = hpass
}
開發者ID:johngoebel,項目名稱:go-programs,代碼行數:7,代碼來源:kittens.go

示例13: saveUser

// Create and save the new user
func (c App) saveUser(user models.User, verifyPassword string) error {

	// Validate the user, make sure passwords are valid ...
	c.Validation.Required(verifyPassword)
	c.Validation.Required(verifyPassword == user.Password).
		Message("Password does not match")
	user.Validate(c.Validation)

	if c.Validation.HasErrors() {
		c.Validation.Keep()
		c.FlashParams()
		return errors.New("Unable to validate input")
	}

	user.HashedPassword, _ = bcrypt.GenerateFromPassword(
		[]byte(user.Password), bcrypt.DefaultCost)

	// Insert the new user into the database
	err := c.Txn.Insert(&user)
	if err != nil {
		return newError("Unable to save user in database", err)
	}

	return nil
}
開發者ID:shaheemirza,項目名稱:CAGo,代碼行數:26,代碼來源:app.go

示例14: newUser

func (user *User) newUser(dataMap map[string]string, res *AccMngResponse) {
	// Hashing password, if hash fails, abort user
	hash, err := bcrypt.GenerateFromPassword([]byte(dataMap["Password"]), 12)
	if err != nil {
		log.Printf("Function addUser: Error when encrypting the password.\n%v\b", err)
		res.Status = false
		res.Message = "Error when encrypting the password"
		return
	}

	// Converting the IsAdmin flag from string to bool
	var flag bool
	switch dataMap["Isadmin"] {
	case "true":
		flag = true
	default:
		flag = false
		// default:
		// 	log.Printf("Function addUser: Error when converting isadmin to boolean.\n")
		// 	res.Status = false
		// 	res.Message = "Error when converting isadmin to boolean"
		// 	return
	}

	user.FirstName = dataMap["Firstname"]
	user.LastName = dataMap["Lastname"]
	user.IsAdmin = flag
	user.Email = dataMap["Email"]
	user.Password = string(hash)
	user.Avatar = dataMap["Avatar"]

	res.Status = true
	res.Message = ""
}
開發者ID:jamesjacko,項目名稱:dewis,代碼行數:34,代碼來源:accountmanager.go

示例15: main

func main() {
	var cliOpts struct {
		Cost int `short:"c" long:"cost" description:"Custom cost factor"`
	}

	cliOpts.Cost = 12

	parser := flags.NewParser(&cliOpts, flags.Default)
	parser.Usage = "PASSWORD"

	args, err := parser.Parse()
	if err != nil {
		panic(err)
	}

	if cliOpts.Cost < bcrypt.MinCost {
		fmt.Printf("Minimum cost is %d.\n", bcrypt.MinCost)
		os.Exit(1)
	} else if cliOpts.Cost > bcrypt.MaxCost {
		fmt.Printf("Maximum cost is %d.\n", bcrypt.MaxCost)
		os.Exit(1)
	}

	if len(args) == 0 {
		parser.WriteHelp(os.Stderr)
		os.Exit(1)
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(args[0]), cliOpts.Cost)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(hash))
}
開發者ID:bigwhoop,項目名稱:bcryptr,代碼行數:35,代碼來源:main.go


注:本文中的code/google/com/p/go/crypto/bcrypt.GenerateFromPassword函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。