forked from mtusi2026/mtusi2026lab7
Реализация на 5
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type profile struct {
|
||||
memory, iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
var slots = make(chan struct{}, 2)
|
||||
|
||||
func desired() (profile, error) {
|
||||
p := profile{65536, 3, 1}
|
||||
for name, dst := range map[string]*uint32{"ARGON2_MEMORY_KIB": &p.memory, "ARGON2_ITERATIONS": &p.iterations} {
|
||||
if s := os.Getenv(name); s != "" {
|
||||
n, e := strconv.ParseUint(s, 10, 32)
|
||||
if e != nil {
|
||||
return p, e
|
||||
}
|
||||
*dst = uint32(n)
|
||||
}
|
||||
}
|
||||
if s := os.Getenv("ARGON2_PARALLELISM"); s != "" {
|
||||
n, e := strconv.ParseUint(s, 10, 8)
|
||||
if e != nil {
|
||||
return p, e
|
||||
}
|
||||
p.parallelism = uint8(n)
|
||||
}
|
||||
return p, check(p)
|
||||
}
|
||||
func check(p profile) error {
|
||||
if p.memory < 19456 || p.memory > 65536 || p.iterations < 2 || p.iterations > 4 || p.parallelism < 1 || p.parallelism > 4 {
|
||||
return fmt.Errorf("unsupported Argon2id resource profile")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func prefix(p profile) string {
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$", p.memory, p.iterations, p.parallelism)
|
||||
}
|
||||
func derive(ctx context.Context, p profile, secret string, salt []byte) ([]byte, error) {
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
defer func() { <-slots }()
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := argon2.IDKey([]byte(secret), salt, p.iterations, p.memory, p.parallelism, 32)
|
||||
return key, ctx.Err()
|
||||
}
|
||||
func (e *encryptor) EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error) {
|
||||
p, err := desired()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
salt := make([]byte, 16)
|
||||
if _, err = rand.Read(salt); err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
}
|
||||
key, err := derive(ctx, p, secret, salt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return prefix(p) + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
func parse(hash string) (profile, []byte, []byte, error) {
|
||||
var p profile
|
||||
if len(hash) > 160 {
|
||||
return p, nil, nil, ErrFailedToComparePasswords
|
||||
}
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||
return p, nil, nil, ErrFailedToComparePasswords
|
||||
}
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil || check(p) != nil || prefix(p) != "$argon2id$v=19$"+parts[3]+"$" {
|
||||
return p, nil, nil, ErrFailedToComparePasswords
|
||||
}
|
||||
enc := base64.RawStdEncoding.Strict()
|
||||
salt, e := enc.DecodeString(parts[4])
|
||||
if e != nil || len(salt) != 16 {
|
||||
return p, nil, nil, ErrFailedToComparePasswords
|
||||
}
|
||||
key, e := enc.DecodeString(parts[5])
|
||||
if e != nil || len(key) != 32 {
|
||||
return p, nil, nil, ErrFailedToComparePasswords
|
||||
}
|
||||
return p, salt, key, nil
|
||||
}
|
||||
func (e *encryptor) CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error {
|
||||
p, salt, stored, err := parse(hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := derive(ctx, p, secret, salt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if subtle.ConstantTimeCompare(stored, key) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func NeedsRehash(hash string) bool {
|
||||
p, e := desired()
|
||||
return e == nil && !strings.HasPrefix(hash, prefix(p))
|
||||
}
|
||||
func ValidateProfile() error { _, e := desired(); return e }
|
||||
@@ -0,0 +1,72 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type encryptor struct {
|
||||
cost int
|
||||
generateFromPasswordFunc func([]byte, int) ([]byte, error)
|
||||
compareHashAndPasswordFunc func([]byte, []byte) error
|
||||
}
|
||||
|
||||
func New() Encryptor {
|
||||
return &encryptor{
|
||||
cost: bcrypt.DefaultCost,
|
||||
generateFromPasswordFunc: bcrypt.GenerateFromPassword,
|
||||
compareHashAndPasswordFunc: bcrypt.CompareHashAndPassword,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, error) {
|
||||
res, err := e.generateFromPasswordFunc([]byte(secret), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
// EncryptSecretUsingSum256 hashes a high-entropy session token, not a password.
|
||||
func (e *encryptor) EncryptSecretUsingSum256(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return "sha256:" + hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(password))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
if payload, ok := strings.CutPrefix(hash, "sha256:"); ok {
|
||||
stored, err := hex.DecodeString(payload)
|
||||
if err != nil || len(stored) != sha256.Size || subtle.ConstantTimeCompare(stored, sum[:]) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Preserve existing lab2/lab3 sessions across a rolling deployment.
|
||||
// Passwords continue to use Argon2id; only old random-token fingerprints use this fallback.
|
||||
if strings.HasPrefix(hash, "$2") {
|
||||
if err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:]))); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package encrypting
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrFailedToEncryptPassword = errors.New("failed to encrypt password")
|
||||
ErrFailedToComparePasswords = errors.New("failed to compare passwords")
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package encrypting
|
||||
|
||||
import "context"
|
||||
|
||||
type Encryptor interface {
|
||||
EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error)
|
||||
CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error
|
||||
EncryptSecret(ctx context.Context, secret string) (string, error)
|
||||
EncryptSecretUsingSum256(_ context.Context, secret string) (string, error)
|
||||
CompareHashAndSecret(ctx context.Context, hash, secret string) error
|
||||
CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionFingerprints(t *testing.T) {
|
||||
e := New()
|
||||
ctx := context.Background()
|
||||
token := "synthetic-high-entropy-session-value"
|
||||
hash, err := e.EncryptSecretUsingSum256(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, hash, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"sha256:00", "sha256:invalid", "unknown"} {
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, bad, token) == nil {
|
||||
t.Fatal("accepted malformed fingerprint")
|
||||
}
|
||||
}
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, hash, token+"x") == nil {
|
||||
t.Fatal("accepted wrong token")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
legacy, err := bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(sum[:])), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, string(legacy), token); err != nil {
|
||||
t.Fatal("legacy session rejected", err)
|
||||
}
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if e.CompareHashAndSecretUsingSum256(canceled, hash, token) == nil {
|
||||
t.Fatal("ignored cancellation")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user