feat: migrate passwords from SHA-256 to bcrypt
- Replace SHA-256 hex hashing with bcrypt (cost 10) for password storage - VerifyPassword now uses bcrypt.CompareHashAndPassword - HashPassword returns (string, error) instead of string - Add IsBcryptHash helper to detect legacy hashes for future migration - Remove duplicate verifyPassword from api.go (already done in prev commit) - Promote golang.org/x/crypto to direct dependency
This commit is contained in:
@@ -4,16 +4,17 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"gitea.mrixs.me/Mrixs/MrixsCraft-server/internal/config"
|
||||
"gitea.mrixs.me/Mrixs/MrixsCraft-server/internal/database"
|
||||
)
|
||||
@@ -380,10 +381,10 @@ func ExtractBearer(h string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// VerifyPassword checks a plaintext password against a SHA-256 hex hash.
|
||||
// VerifyPassword checks a plaintext password against a stored bcrypt hash.
|
||||
func VerifyPassword(password, hash string) bool {
|
||||
h := sha256.Sum256([]byte(password))
|
||||
return subtle.ConstantTimeCompare([]byte(hex.EncodeToString(h[:])), []byte(hash)) == 1
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// GenerateToken creates a random hex token (16 bytes → 32 hex chars).
|
||||
@@ -406,12 +407,24 @@ func writeError(w http.ResponseWriter, status int, err, msg string) {
|
||||
})
|
||||
}
|
||||
|
||||
// HashPassword returns the SHA-256 hex of a password for storage.
|
||||
func HashPassword(password string) string {
|
||||
h := sha256.Sum256([]byte(password))
|
||||
return hex.EncodeToString(h[:])
|
||||
// HashPassword returns a bcrypt hash of the password for storage.
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("hashing password: %w", err)
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// IsBcryptHash reports whether the given hash looks like a bcrypt hash
|
||||
// (starts with $2a$, $2b$, or $2y$). Used to detect legacy SHA-256 hashes.
|
||||
func IsBcryptHash(hash string) bool {
|
||||
return strings.HasPrefix(hash, "$2a$") || strings.HasPrefix(hash, "$2b$") || strings.HasPrefix(hash, "$2y$")
|
||||
}
|
||||
|
||||
// ErrPasswordHashing is returned when bcrypt hashing fails.
|
||||
var ErrPasswordHashing = errors.New("password hashing failed")
|
||||
|
||||
// GenerateUUID creates a random UUID v4-like string.
|
||||
func GenerateUUID() string {
|
||||
b := make([]byte, 16)
|
||||
|
||||
Reference in New Issue
Block a user