feat: 优化密保规则支持最低1位且无上限
This commit is contained in:
1 parent
187caebe0c
commit
169730436f
5 files changed
+52
-20
No files matched your search
@@ -22,8 +22,7 @@ const (
|
||||
saltLength = 16
|
||||
keyLength = 32
|
||||
maxHashSize = 255
|
||||
minSecretSize = 8
|
||||
maxSecretSize = 256
|
||||
minSecretSize = 1
|
||||
minPasswordSize = 8
|
||||
maxPasswordSize = 12
|
||||
)
|
||||
@@ -41,7 +40,7 @@ func ValidateUserPassword(plain string) error {
|
||||
// Hash 生成 Argon2id 密码哈希。
|
||||
func Hash(plain string) (string, error) {
|
||||
plainSize := len([]byte(plain))
|
||||
if plainSize < minSecretSize || plainSize > maxSecretSize {
|
||||
if plainSize < minSecretSize {
|
||||
return "", ErrInvalidLength
|
||||
}
|
||||
salt := make([]byte, saltLength)
|
||||
@@ -83,7 +82,7 @@ func HashUserPassword(plain string) (string, error) {
|
||||
|
||||
// Verify 校验 Argon2id 密码哈希,不接受旧算法格式。
|
||||
func Verify(encoded, plain string) bool {
|
||||
if len([]byte(plain)) > maxSecretSize {
|
||||
if len([]byte(plain)) < minSecretSize {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(encoded, "$")
|
||||
|
||||
@@ -16,14 +16,21 @@ func TestHashAndVerify(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashRejectsInvalidLengths(t *testing.T) {
|
||||
for _, plain := range []string{"short", strings.Repeat("a", maxSecretSize+1)} {
|
||||
if _, err := Hash(plain); err == nil {
|
||||
t.Fatalf("invalid secret length was accepted: %d", len([]byte(plain)))
|
||||
func TestHashSupportsSingleCharacterAndLongInputs(t *testing.T) {
|
||||
for _, plain := range []string{"a", "中", strings.Repeat("long-secret-key-123", 50)} {
|
||||
encoded, err := Hash(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("valid secret %q failed: %v", plain, err)
|
||||
}
|
||||
if !Verify(encoded, plain) {
|
||||
t.Fatalf("verification failed for %q", plain)
|
||||
}
|
||||
}
|
||||
if Verify(mustHash(t, "StrongPass123"), strings.Repeat("a", maxSecretSize+1)) {
|
||||
t.Fatal("oversized verification input was accepted")
|
||||
if _, err := Hash(""); !errors.Is(err, ErrInvalidLength) {
|
||||
t.Fatalf("empty secret should be rejected, got: %v", err)
|
||||
}
|
||||
if Verify(mustHash(t, "StrongPass123"), "") {
|
||||
t.Fatal("empty verification input was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user