github.com/emmansun/gmsm@v0.29.1/cipher/ccm_sm4_test.go (about)

     1  package cipher_test
     2  
     3  import (
     4  	"encoding/hex"
     5  	"testing"
     6  
     7  	smcipher "github.com/emmansun/gmsm/cipher"
     8  	"github.com/emmansun/gmsm/sm4"
     9  )
    10  
    11  var sm4CCMTests = []struct {
    12  	key, nonce, plaintext, ad, result string
    13  }{
    14  	{ // https://tools.ietf.org/html/rfc8998 A.2. SM4-CCM Test Vectors
    15  		"0123456789abcdeffedcba9876543210",
    16  		"00001234567800000000abcd",
    17  		"aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbccccccccccccccccddddddddddddddddeeeeeeeeeeeeeeeeffffffffffffffffeeeeeeeeeeeeeeeeaaaaaaaaaaaaaaaa",
    18  		"feedfacedeadbeeffeedfacedeadbeefabaddad2",
    19  		"48af93501fa62adbcd414cce6034d895dda1bf8f132f042098661572e7483094fd12e518ce062c98acee28d95df4416bed31a2f04476c18bb40c84a74b97dc5b16842d4fa186f56ab33256971fa110f4",
    20  	},
    21  }
    22  
    23  func TestCCM(t *testing.T) {
    24  	for i, tt := range sm4CCMTests {
    25  		nonce, _ := hex.DecodeString(tt.nonce)
    26  		plaintext, _ := hex.DecodeString(tt.plaintext)
    27  		ad, _ := hex.DecodeString(tt.ad)
    28  		key, _ := hex.DecodeString(tt.key)
    29  		tagSize := (len(tt.result) - len(tt.plaintext)) / 2
    30  		c, err := sm4.NewCipher(key)
    31  		if err != nil {
    32  			t.Fatal(err)
    33  		}
    34  		sm4ccm, err := smcipher.NewCCMWithNonceAndTagSize(c, len(nonce), tagSize)
    35  		if err != nil {
    36  			t.Fatal(err)
    37  		}
    38  		ct := sm4ccm.Seal(nil, nonce, plaintext, ad)
    39  		if ctHex := hex.EncodeToString(ct); ctHex != tt.result {
    40  			t.Errorf("#%d: got %s, want %s", i, ctHex, tt.result)
    41  			continue
    42  		}
    43  
    44  		//func (c *ccm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
    45  		pt, err := sm4ccm.Open(nil, nonce, ct, ad)
    46  		if err != nil {
    47  			t.Fatal(err)
    48  		}
    49  		if ptHex := hex.EncodeToString(pt); ptHex != tt.plaintext {
    50  			t.Errorf("#%d: got %s, want %s", i, ptHex, tt.plaintext)
    51  			continue
    52  		}
    53  	}
    54  }