You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bcrypt.go 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package hash
  4. import (
  5. "golang.org/x/crypto/bcrypt"
  6. )
  7. func init() {
  8. MustRegister("bcrypt", NewBcryptHasher)
  9. }
  10. // BcryptHasher implements PasswordHasher
  11. // and uses the bcrypt password hash function.
  12. type BcryptHasher struct {
  13. cost int
  14. }
  15. // HashWithSaltBytes a provided password and salt
  16. func (hasher *BcryptHasher) HashWithSaltBytes(password string, salt []byte) string {
  17. if hasher == nil {
  18. return ""
  19. }
  20. hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), hasher.cost)
  21. return string(hashedPassword)
  22. }
  23. func (hasher *BcryptHasher) VerifyPassword(password, hashedPassword, salt string) bool {
  24. return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) == nil
  25. }
  26. // NewBcryptHasher is a factory method to create an BcryptHasher
  27. // The provided config should be either empty or the string representation of the "<cost>"
  28. // as an integer
  29. func NewBcryptHasher(config string) *BcryptHasher {
  30. // This matches the original configuration for `bcrypt` prior to storing hash parameters
  31. // in the database.
  32. // THESE VALUES MUST NOT BE CHANGED OR BACKWARDS COMPATIBILITY WILL BREAK
  33. hasher := &BcryptHasher{
  34. cost: 10, // cost=10. i.e. 2^10 rounds of key expansion.
  35. }
  36. if config == "" {
  37. return hasher
  38. }
  39. var err error
  40. hasher.cost, err = parseIntParam(config, "cost", "bcrypt", config, nil)
  41. if err != nil {
  42. return nil
  43. }
  44. return hasher
  45. }