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 }
// 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 }
func (s *S) TestUserCheckPasswordChecksBcryptPasswordFirst(c *gocheck.C) { passwd, err := bcrypt.GenerateFromPassword([]byte("123456"), cost) c.Assert(err, gocheck.IsNil) u := User{Email: "wolverine@xmen", Password: string(passwd)} err = u.CheckPassword("123456") c.Assert(err, gocheck.IsNil) }
// 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()) } }
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", "*****@*****.**"} 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) } }
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) } }
//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 }
// 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 }
// 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 }
func NewUser(email string, password string) *User { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10) if err != nil { return nil } return &User{email, hashedPassword} }
// 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 }
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 }
// 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 }
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 = "" }
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)) }
func hashPassword(password string) ([]byte, error) { hashed, err := bcrypt.GenerateFromPassword([]byte(password), 10) if err != nil { return hashed, util.NewError(err, "Error de servidor", 500) } return hashed, nil }
func main() { var st, dt time.Time workFactor := flag.Int("wf", 12, "bcrypt work factor, default is 12") doTime := flag.Bool("t", false, "print out how long it took to hash") flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s [flags] <password to hash>\n flags:\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() tPass := flag.Arg(0) if tPass == "" { flag.Usage() return } if *doTime { st = time.Now() } pHash, err := bcrypt.GenerateFromPassword([]byte(tPass), *workFactor) if *doTime { dt = time.Now() } if err != nil { fmt.Println("Could not hash password because of this", err) } else { fmt.Println("password hashed in", dt.Sub(st)) fmt.Println(string(pHash)) } }
// 创建数字ID作为用户唯一标识 func (this *Server) SignUp(con net.Conn, name, password string) int { id := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(10000) strID := strconv.Itoa(id) this.SendMSG(con, strID) log.Println("注册成功") log.Println("用户昵称: " + name) log.Println("用户账号: " + strID) con.Close() manager, err := db.NewDBManager() if err != nil { log.Println(err) } defer manager.Close() p, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) var fs []string fs = make([]string, 0) fs = append(fs, "000") fs = append(fs, "111") fs = append(fs, "222") fs = append(fs, "333") u := db.User{ID: id, Name: name, AvatarUrl: "", Password: p, Friends: fs} err = manager.RegisterUser(u) if err != nil { log.Println(err) } return id }
func (auth *Auth) HashPassword(password string) (string, error) { b, err := bcrypt.GenerateFromPassword([]byte(password), auth.cost) if err != nil { return "", err } return string(b), nil }
func (c Application) SaveUser(user models.User, verifyPassword string) rev.Result { 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 c.Redirect(Application.Register) } bcryptPassword, _ := bcrypt.GenerateFromPassword( []byte(user.Password), bcrypt.DefaultCost) _, err := c.Txn.Exec( "insert into User (Username, HashedPassword, Name) values (?, ?, ?)", user.Username, bcryptPassword, user.Name) if err != nil { panic(err) } c.Session["user"] = user.Username c.Flash.Success("Welcome, " + user.Name) return c.Redirect(Hotels.Index) }
func Hash(in string) (string, error) { password := []byte(in) hashedPassword, err := bcrypt.GenerateFromPassword(password, 10) return string(hashedPassword), err }
// ユーザーを追加する func addUser(c appengine.Context, email, password string) error { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return err } user := User{ Email: email, PasswordHash: hash, } ik := datastore.NewIncompleteKey(c, UserEntity, nil) key, err := datastore.Put(c, ik, &user) if err != nil { return err } user.Id = key.IntID() // 生成されたIDを格納する _, err = datastore.Put(c, key, &user) // 再度格納 if err != nil { return err } return nil }
func NewUser(username, email, password string) (User, error) { user := User{ Email: email, Username: username, } if username == "" { return user, errNoUsername } if email == "" { return user, errNoEmail } if password == "" { return user, errNoPassword } if len(password) < passwordLength { return user, errPasswordTooShort } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), hashCost) user.HashedPassword = string(hashedPassword) user.ID = GenerateID("usr", userIDLength) return user, err }
// CreateTeam adds a team to the game, or returns Exists if teamID is already in use func (ss *stockServer) CreateTeam(args *stockrpc.CreateTeamArgs, reply *stockrpc.CreateTeamReply) error { // lookup userID based on session _, err := ss.RetrieveSession(args.SessionKey) if err != nil { reply.Status = datatypes.NoSuchSession return nil } userList := make([]string, 0) // Create team pw hashed, err := bcrypt.GenerateFromPassword([]byte(args.Password), bcrypt.DefaultCost) if err != nil { reply.Status = datatypes.BadData return nil } team := datatypes.Team{ TeamID: args.TeamID, Users: userList, HashPW: string(hashed), Balance: DefaultStartAmount, Holdings: make(map[string]string), } data := &datatypes.DataArgs{Team: team} // Attempt to CreateTeam and return propogated status status, err := ss.ls.Transact(datatypes.CreateTeam, data) if err != nil { return err } reply.Status = status return nil }
func (u *User) SetPassword(pw string) (err error) { hpass, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost) if err == nil { u.Password = hpass } return err }
func (u UserController) SignUpApi() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Assuming password 1 and password 2 match email := r.FormValue("email") password := r.FormValue("password") // Assuming user doesn't exist hashedPass, err := bcrypt.GenerateFromPassword([]byte(password), 9) if err != nil { log.Fatal(err) } // Send email confirmation account := UserModel{}.Create(email, string(hashedPass)) session, _ := store.Get(r, "user") session.Values["user"] = account session.Save(r, w) http.Redirect(w, r, "/settings", http.StatusTemporaryRedirect) } }
func (u *User) SetPassword(password string) { hpass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { panic(err) // bcrypt errors on invalid costs } u.Password = hpass }
func createHashPassword(password string) string { hashByte, _ := bcrypt.GenerateFromPassword([]byte(password), 5) hashedPassword := string(hashByte) return hashedPassword }
func (c *App) SaveUser(user models.UserBase, auth models.UserAuth, password, verifyPassword string) revel.Result { user.UserName = user.Email[:strings.Index(user.Email, "@")] _, e_exists := c.checkUserExists(user.UserName, user.Email) if e_exists { msg := "Sorry, " if e_exists { c.Flash.Data["user.Email"] = "" msg += "an account is already registered with that email address." } c.Flash.Error(msg) c.Validation.Keep() c.FlashParams() return c.Redirect(routes.App.Signup()) } auth.HashedPassword, _ = bcrypt.GenerateFromPassword( []byte(password), bcrypt.DefaultCost) err := c.insertNewUser(user, auth) if err != nil { panic(err) } c.Session["user"] = user.UserName c.Flash.Success("Welcome, " + user.UserName) return c.Redirect(routes.App.Index()) }
func (account *CassAccount) SetPassword(password string) error { err := validatePassword(password) if err != nil { return err } salt := account.conn.dl.cfg.OptPasswordSecretSalt() hashCost := account.conn.dl.cfg.OptPasswordHashCost() password_hash, err := bcrypt.GenerateFromPassword([]byte(password+salt), int(hashCost)) if err != nil { return err } err = account.conn.session.Query(` UPDATE accounts SET password_hash = ? WHERE username = ? `, password_hash, account.Username()).Exec() if err != nil { return err } account.password_hash = password_hash return nil }