github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/grypto/grypto_test.go (about)

     1  package grypto
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/gramework/gramework/grypto/providers/bcrypt"
     7  	"github.com/gramework/gramework/grypto/providers/scrypt"
     8  	"github.com/gramework/utils/grand"
     9  )
    10  
    11  func TestProviderMatchingAndSanity(t *testing.T) {
    12  	p1 := scrypt.New()
    13  	p2 := bcrypt.New()
    14  
    15  	pw := make([]byte, 12)
    16  	grand.Read(pw)
    17  
    18  	phash1 := p1.Hash(pw)
    19  	phash2 := p2.Hash(pw)
    20  
    21  	if !p1.Valid(phash1, pw) {
    22  		t.Error("p1 validation failed with original password")
    23  		return
    24  	}
    25  
    26  	if !p2.Valid(phash2, pw) {
    27  		t.Error("p2 validation failed with original password")
    28  		return
    29  	}
    30  
    31  	if p1.Valid(phash2, pw) {
    32  		t.Error("p1 validation succeed with original password but phash2")
    33  		return
    34  	}
    35  
    36  	if p2.Valid(phash1, pw) {
    37  		t.Error("p2 validation succeed with original password but phash1")
    38  		return
    39  	}
    40  
    41  	if !PasswordValid(phash1, pw) {
    42  		t.Error("phash1 matching validation failed with original password")
    43  		return
    44  	}
    45  
    46  	if !PasswordValid(phash2, pw) {
    47  		t.Error("phash2 matching validation failed with original password")
    48  		return
    49  	}
    50  
    51  	var pwc = make([]byte, 12)
    52  	copy(pwc, pw)
    53  
    54  	pwc[2] ^= pwc[0]
    55  	pwc[3] ^= pwc[2]
    56  
    57  	if p1.Valid(phash1, pwc) {
    58  		t.Error("p1 validation succeed with modified password")
    59  		return
    60  	}
    61  
    62  	if p2.Valid(phash2, pwc) {
    63  		t.Error("p2 validation succeed with modified password")
    64  		return
    65  	}
    66  
    67  	if p1.Valid(phash2, pwc) {
    68  		t.Error("p1 validation succeed with modified password but phash2")
    69  		return
    70  	}
    71  
    72  	if p2.Valid(phash1, pwc) {
    73  		t.Error("p2 validation succeed with modified password but phash1")
    74  		return
    75  	}
    76  }