sha-512 hash passwords longer than 72 bytes (#4331)

* sha-512 hash passwords longer than 72 bytes

* rename compress_hashing to go conventions

* add api test for long passwords

* fix typo

* chore(test): add unit test for password hashing

---------

Co-authored-by: Gabe Kangas <gabek@real-ity.com>
This commit is contained in:
mahmed2000
2025-10-14 03:05:42 +05:00
committed by GitHub
parent 4e0becc2e0
commit f30b80d473
5 changed files with 369 additions and 5 deletions

View File

@ -1,15 +1,28 @@
package utils
import (
"crypto/sha512"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (string, error) {
password_bytes := compressPassword([]byte(password))
// 0 will use the default cost of 10 instead
hash, err := bcrypt.GenerateFromPassword([]byte(password), 0)
hash, err := bcrypt.GenerateFromPassword(password_bytes, 0)
return string(hash), err
}
func ComparseHash(hash string, password string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
func CompareHash(hash string, password string) error {
password_bytes := compressPassword([]byte(password))
return bcrypt.CompareHashAndPassword([]byte(hash), password_bytes)
}
// Takes a password and computes a sha-512 hash of it if it is longer than 72 bytes, guaranteeing it is less than 72 bytes long.
func compressPassword(password []byte) []byte {
if len(password) > 72 {
sha512_hashed := sha512.Sum512(password)
password = sha512_hashed[:]
}
return password
}