code.gitea.io/gitea@v1.19.3/modules/auth/password/hash/bcrypt.go (about)

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