hashing.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package permissionsql
  2. import (
  3. "crypto/sha256"
  4. "crypto/subtle"
  5. "golang.org/x/crypto/bcrypt"
  6. "io"
  7. )
  8. // Hash the password with sha256 (the username is needed for salting)
  9. func hash_sha256(cookieSecret, username, password string) []byte {
  10. hasher := sha256.New()
  11. // Use the cookie secret as additional salt
  12. io.WriteString(hasher, password+cookieSecret+username)
  13. return hasher.Sum(nil)
  14. }
  15. // Hash the password with bcrypt
  16. func hash_bcrypt(password string) []byte {
  17. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  18. if err != nil {
  19. panic("Permissions: bcrypt password hashing unsuccessful")
  20. }
  21. return hash
  22. }
  23. // Check if a given password(+username) is correct, for a given sha256 hash
  24. func correct_sha256(hash []byte, cookieSecret, username, password string) bool {
  25. comparisonHash := hash_sha256(cookieSecret, username, password)
  26. // check that the lengths are equal before calling ConstantTimeCompare
  27. if len(hash) != len(comparisonHash) {
  28. return false
  29. }
  30. // prevents timing attack
  31. return subtle.ConstantTimeCompare(hash, comparisonHash) == 1
  32. }
  33. // Check if a given password is correct, for a given bcrypt hash
  34. func correct_bcrypt(hash []byte, password string) bool {
  35. // prevents timing attack
  36. return bcrypt.CompareHashAndPassword(hash, []byte(password)) == nil
  37. }
  38. // Check if the given hash is sha256 (when the alternative is only bcrypt)
  39. func is_sha256(hash []byte) bool {
  40. return len(hash) == 32
  41. }