github.com/emmansun/gmsm@v0.29.1/pkcs/kdf_pbkdf2_test.go (about)

     1  package pkcs
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/sha1"
     6  	"crypto/x509/pkix"
     7  	"testing"
     8  
     9  	"github.com/emmansun/gmsm/sm3"
    10  )
    11  
    12  func TestNewHashFromPRF(t *testing.T) {
    13  	h, err := newHashFromPRF(oidPKCS5PBKDF2, pkix.AlgorithmIdentifier{})
    14  	if err != nil {
    15  		t.Errorf("unexpected error: %v", err)
    16  	}
    17  	hash := h()
    18  	if hash.Size() != sha1.Size {
    19  		t.Errorf("unexpected hash size: got %d, want %d", hash.Size(), sha1.Size)
    20  	}
    21  	h, err = newHashFromPRF(oidSMPBKDF, pkix.AlgorithmIdentifier{})
    22  	if err != nil {
    23  		t.Errorf("unexpected error: %v", err)
    24  	}
    25  	hash = h()
    26  	if hash.Size() != sm3.Size {
    27  		t.Errorf("unexpected hash size: got %d, want %d", hash.Size(), sm3.Size)
    28  	}
    29  }
    30  
    31  func TestPBKDF2DeriveKey(t *testing.T) {
    32  	testCases := []struct {
    33  		name string
    34  		opts PBKDF2Opts
    35  	}{
    36  		{
    37  			name: "PBKDF2-SHA1",
    38  			opts: NewPBKDF2Opts(SHA1, 16, 1000),
    39  		},
    40  		{
    41  			name: "PBKDF2-SHA256",
    42  			opts: NewPBKDF2Opts(SHA256, 16, 1000),
    43  		},
    44  		{
    45  			name: "SMPBKDF2",
    46  			opts: NewSMPBKDF2Opts(16, 1000),
    47  		},
    48  	}
    49  	for _, tc := range testCases {
    50  		t.Run(tc.name, func(t *testing.T) {
    51  			key, params, err := tc.opts.DeriveKey([]byte("password"), []byte("saltsaltsaltsalt"), 32)
    52  			if err != nil {
    53  				t.Errorf("unexpected error: %v", err)
    54  			}
    55  			if len(key) != 32 {
    56  				t.Errorf("unexpected key length: got %d, want 32", len(key))
    57  			}
    58  			if params.KeyLength() != 32 {
    59  				t.Errorf("unexpected key length: got %d, want 32", params.KeyLength())
    60  			}
    61  			if len(params.(pbkdf2Params).Salt) != tc.opts.SaltSize {
    62  				t.Errorf("unexpected salt length: got %d, want %d", len(params.(pbkdf2Params).Salt), tc.opts.SaltSize)
    63  			}
    64  			if params.(pbkdf2Params).IterationCount != tc.opts.IterationCount {
    65  				t.Errorf("unexpected iteration count: got %d, want %d", params.(pbkdf2Params).IterationCount, tc.opts.IterationCount)
    66  			}
    67  			if params.(pbkdf2Params).KeyLen != 32 {
    68  				t.Errorf("unexpected key length: got %d, want 32", params.(pbkdf2Params).KeyLen)
    69  			}
    70  			key2, err := params.DeriveKey(nil, []byte("password"), 32)
    71  			if err != nil {
    72  				t.Errorf("unexpected error: %v", err)
    73  			}
    74  			if !bytes.Equal(key, key2) {
    75  				t.Errorf("unexpected key: got %x, want %x", key2, key)
    76  			}
    77  		})
    78  	}
    79  }