forked from mtusi2026/mtusi2026lab3
44 lines
1.2 KiB
Go
44 lines
1.2 KiB
Go
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")
|
|
}
|
|
}
|