git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/crypto/password_test.go (about)

     1  package crypto
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  func TestHashPassword(t *testing.T) {
    10  	hashRX, err := regexp.Compile(`^\$argon2id\$v=19\$m=65536,t=3,p=2\$[A-Za-z0-9+/]{86}\$[A-Za-z0-9+/]{86}$`)
    11  	if err != nil {
    12  		t.Fatal(err)
    13  	}
    14  
    15  	hash1, err := HashPassword([]byte("pa$$word"), DefaultHashPasswordParams)
    16  	if err != nil {
    17  		t.Fatal(err)
    18  	}
    19  
    20  	if !hashRX.MatchString(hash1) {
    21  		t.Errorf("hash %q not in correct format", hash1)
    22  	}
    23  
    24  	hash2, err := HashPassword([]byte("pa$$word"), DefaultHashPasswordParams)
    25  	if err != nil {
    26  		t.Fatal(err)
    27  	}
    28  
    29  	if strings.Compare(hash1, hash2) == 0 {
    30  		t.Error("hashes must be unique")
    31  	}
    32  }
    33  
    34  func TestVerifyPasswordHash(t *testing.T) {
    35  	hash, err := HashPassword([]byte("pa$$word"), DefaultHashPasswordParams)
    36  	if err != nil {
    37  		t.Fatal(err)
    38  	}
    39  
    40  	match := VerifyPasswordHash([]byte("pa$$word"), hash)
    41  
    42  	if !match {
    43  		t.Error("expected password and hash to match")
    44  	}
    45  
    46  	match = VerifyPasswordHash([]byte("otherPa$$word"), hash)
    47  
    48  	if match {
    49  		t.Error("expected password and hash to not match")
    50  	}
    51  }