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.

pbkdf2.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package hash
  4. import (
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "strings"
  8. "code.gitea.io/gitea/modules/log"
  9. "golang.org/x/crypto/pbkdf2"
  10. )
  11. func init() {
  12. MustRegister("pbkdf2", NewPBKDF2Hasher)
  13. }
  14. // PBKDF2Hasher implements PasswordHasher
  15. // and uses the PBKDF2 key derivation function.
  16. type PBKDF2Hasher struct {
  17. iter, keyLen int
  18. }
  19. // HashWithSaltBytes a provided password and salt
  20. func (hasher *PBKDF2Hasher) HashWithSaltBytes(password string, salt []byte) string {
  21. if hasher == nil {
  22. return ""
  23. }
  24. return hex.EncodeToString(pbkdf2.Key([]byte(password), salt, hasher.iter, hasher.keyLen, sha256.New))
  25. }
  26. // NewPBKDF2Hasher is a factory method to create an PBKDF2Hasher
  27. // config should be either empty or of the form:
  28. // "<iter>$<keyLen>", where <x> is the string representation
  29. // of an integer
  30. func NewPBKDF2Hasher(config string) *PBKDF2Hasher {
  31. // This default configuration uses the following parameters:
  32. // iter=10000, keyLen=50.
  33. // This matches the original configuration for `pbkdf2` prior to storing parameters
  34. // in the database.
  35. // THESE VALUES MUST NOT BE CHANGED OR BACKWARDS COMPATIBILITY WILL BREAK
  36. hasher := &PBKDF2Hasher{
  37. iter: 10_000,
  38. keyLen: 50,
  39. }
  40. if config == "" {
  41. return hasher
  42. }
  43. vals := strings.SplitN(config, "$", 2)
  44. if len(vals) != 2 {
  45. log.Error("invalid pbkdf2 hash spec %s", config)
  46. return nil
  47. }
  48. var err error
  49. hasher.iter, err = parseIntParam(vals[0], "iter", "pbkdf2", config, nil)
  50. hasher.keyLen, err = parseIntParam(vals[1], "keyLen", "pbkdf2", config, err)
  51. if err != nil {
  52. return nil
  53. }
  54. return hasher
  55. }