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

     1  package crypto
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  )
     7  
     8  func TestMacLen(t *testing.T) {
     9  	data := []byte("com.bloom42.gobox")
    10  	key, err := RandBytes(KeySize512)
    11  	if err != nil {
    12  		t.Error(err)
    13  	}
    14  
    15  	_, err = Mac(key, data, 128)
    16  	if err == nil {
    17  		t.Error("Accept invalid keyLen")
    18  	}
    19  
    20  	_, err = Mac(key, data, 65)
    21  	if err == nil {
    22  		t.Error("Accept invalid keyLen")
    23  	}
    24  
    25  	_, err = Mac(key, data, 0)
    26  	if err == nil {
    27  		t.Error("Accept invalid keyLen")
    28  	}
    29  
    30  	_, err = Mac(key, data, 1)
    31  	if err != nil {
    32  		t.Error("Reject valid keyLen")
    33  	}
    34  
    35  	_, err = Mac(key, data, 64)
    36  	if err != nil {
    37  		t.Error("Reject valid keyLen")
    38  	}
    39  }
    40  
    41  func TestMac(t *testing.T) {
    42  	data1 := []byte("com.bloom42.gobox1")
    43  	data2 := []byte("com.bloom42.gobox2")
    44  	key1, err := RandBytes(KeySize512)
    45  	if err != nil {
    46  		t.Error(err)
    47  	}
    48  	key2, err := RandBytes(KeySize512)
    49  	if err != nil {
    50  		t.Error(err)
    51  	}
    52  
    53  	signature1, err := Mac(key1, data1, KeySize256)
    54  	if err != nil {
    55  		t.Error(err)
    56  	}
    57  
    58  	signature2, err := Mac(key1, data2, KeySize256)
    59  	if err != nil {
    60  		t.Error(err)
    61  	}
    62  
    63  	if bytes.Equal(signature1, signature2) {
    64  		t.Error("signature1 and signature2 are equal")
    65  	}
    66  
    67  	signature3, err := Mac(key1, data1, KeySize256)
    68  	if err != nil {
    69  		t.Error(err)
    70  	}
    71  
    72  	if !bytes.Equal(signature1, signature3) {
    73  		t.Error("signature1 and signature3 are different")
    74  	}
    75  
    76  	signature4, err := Mac(key2, data1, KeySize256)
    77  	if err != nil {
    78  		t.Error(err)
    79  	}
    80  
    81  	if bytes.Equal(signature1, signature4) {
    82  		t.Error("subKey1 and signature4 are equal")
    83  	}
    84  }