github.com/birneee/aes6@v0.0.0-20240131140838-9e8f775f7eae/aes6_test.go (about)

     1  package aes6
     2  
     3  import (
     4  	"crypto/aes"
     5  	"github.com/stretchr/testify/assert"
     6  	"testing"
     7  )
     8  
     9  func testAesGcmWithTagSize(t *testing.T, tagSize int) (tag []byte, err error) {
    10  	var key [16]byte
    11  	var nonce [12]byte
    12  	block, err := aes.NewCipher(key[:])
    13  	assert.NoError(t, err)
    14  
    15  	aesgcm, err := NewGCMWithTagSize(block, tagSize)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  	plaintext := []byte("hello aes")
    20  	ciphertext := aesgcm.Seal(nil, nonce[:], plaintext, nil)
    21  	assert.Equal(t, len(plaintext)+tagSize, len(ciphertext))
    22  	openedtext, err := aesgcm.Open(nil, nonce[:], ciphertext, nil)
    23  	assert.NoError(t, err)
    24  	assert.Equal(t, plaintext, openedtext)
    25  	return ciphertext[len(plaintext):], nil
    26  }
    27  
    28  func TestAesGcm(t *testing.T) {
    29  	var previousTag []byte
    30  	for i := 6; i < 16; i++ {
    31  		tag, err := testAesGcmWithTagSize(t, i)
    32  		assert.NoError(t, err)
    33  		if previousTag != nil {
    34  			assert.Equal(t, previousTag, tag[:len(previousTag)])
    35  		}
    36  		previousTag = tag
    37  	}
    38  }
    39  
    40  func TestAesGcm5(t *testing.T) {
    41  	_, err := testAesGcmWithTagSize(t, 5)
    42  	assert.ErrorContains(t, err, "incorrect tag size")
    43  }
    44  
    45  func TestAesGcm17(t *testing.T) {
    46  	_, err := testAesGcmWithTagSize(t, 17)
    47  	assert.ErrorContains(t, err, "incorrect tag size")
    48  }