From 24637cf61dc34c1f061df7addebff9d836578b60 Mon Sep 17 00:00:00 2001 From: Sun Yimin Date: Fri, 4 Aug 2023 08:25:16 +0800 Subject: [PATCH] sm4: add test cases, cover more plaintext length --- cipher/ecb_sm4_test.go | 6 +++--- cipher/gcm_sm4_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/cipher/ecb_sm4_test.go b/cipher/ecb_sm4_test.go index cc29bee..2a7b773 100644 --- a/cipher/ecb_sm4_test.go +++ b/cipher/ecb_sm4_test.go @@ -94,8 +94,8 @@ func TestECBBasic(t *testing.T) { func TestECBRandom(t *testing.T) { key := []byte("0123456789ABCDEF") - plaintext := make([]byte, 448) - ciphertext := make([]byte, 448) + plaintext := make([]byte, 464) + ciphertext := make([]byte, 464) io.ReadFull(rand.Reader, plaintext) c, err := sm4.NewCipher(key) if err != nil { @@ -103,7 +103,7 @@ func TestECBRandom(t *testing.T) { } encrypter := cipher.NewECBEncrypter(c) encrypter.CryptBlocks(ciphertext, plaintext) - result := make([]byte, 448) + result := make([]byte, 464) decrypter := cipher.NewECBDecrypter(c) decrypter.CryptBlocks(result, ciphertext) if !bytes.Equal(result, plaintext) { diff --git a/cipher/gcm_sm4_test.go b/cipher/gcm_sm4_test.go index 67a2010..7bfca9c 100644 --- a/cipher/gcm_sm4_test.go +++ b/cipher/gcm_sm4_test.go @@ -3,7 +3,9 @@ package cipher_test import ( "bytes" "crypto/cipher" + "crypto/rand" "encoding/hex" + "io" "testing" "github.com/emmansun/gmsm/sm4" @@ -391,3 +393,28 @@ func TestGCMCounterWrap(t *testing.T) { } } } + +func TestSM4GCMRandom(t *testing.T) { + key := []byte("0123456789ABCDEF") + nonce := []byte("0123456789AB") + plaintext := make([]byte, 464) + + io.ReadFull(rand.Reader, plaintext) + c, err := sm4.NewCipher(key) + if err != nil { + t.Fatal(err) + } + aead, err := cipher.NewGCMWithNonceSize(c, len(nonce)) + if err != nil { + t.Fatal(err) + } + got := aead.Seal(nil, nonce, plaintext, nil) + + result, err := aead.Open(nil, nonce, got, nil) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(result, plaintext) { + t.Error("gcm seal/open 464 bytes fail") + } +}