forked from mtusi2026/mtusi2026lab3
45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
package messenger
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/scrypt"
|
|
)
|
|
|
|
const scryptN, scryptR, scryptP = 32768, 8, 1
|
|
|
|
func hashPassword(password string) (string, error) {
|
|
salt := make([]byte, 16)
|
|
if _, err := rand.Read(salt); err != nil {
|
|
return "", err
|
|
}
|
|
hash, err := scrypt.Key([]byte(password), salt, scryptN, scryptR, scryptP, 32)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
b64 := base64.RawStdEncoding
|
|
return fmt.Sprintf("scrypt$%d$%d$%d$%s$%s", scryptN, scryptR, scryptP, b64.EncodeToString(salt), b64.EncodeToString(hash)), nil
|
|
}
|
|
|
|
func verifyPassword(encoded, password string) bool {
|
|
parts := strings.Split(encoded, "$")
|
|
if len(parts) != 6 || parts[0] != "scrypt" {
|
|
return false
|
|
}
|
|
n, e1 := strconv.Atoi(parts[1])
|
|
r, e2 := strconv.Atoi(parts[2])
|
|
p, e3 := strconv.Atoi(parts[3])
|
|
salt, e4 := base64.RawStdEncoding.DecodeString(parts[4])
|
|
expected, e5 := base64.RawStdEncoding.DecodeString(parts[5])
|
|
if e1 != nil || e2 != nil || e3 != nil || e4 != nil || e5 != nil || len(expected) != 32 {
|
|
return false
|
|
}
|
|
actual, err := scrypt.Key([]byte(password), salt, n, r, p, len(expected))
|
|
return err == nil && subtle.ConstantTimeCompare(actual, expected) == 1
|
|
}
|