Реализована лабораторная 6 на оценку 4

This commit is contained in:
MacBook
2026-11-16 15:16:54 +03:00
parent 470d9d6f1e
commit 4262a16ada
64 changed files with 8467 additions and 43 deletions
+44
View File
@@ -0,0 +1,44 @@
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
}