github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/jls/aes_gcm_256_test.go (about)

     1  package jls
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestAESGCM(t *testing.T) {
    11  	// check len
    12  	cipherTextAndMac, err := Encrypt([]byte("key"), []byte("key"), []byte("key"))
    13  	assert.NotNil(t, err)
    14  	assert.Empty(t, cipherTextAndMac)
    15  
    16  	key := sha256.New()
    17  	key.Write([]byte("key"))
    18  	plainText := []byte("cipherText")
    19  
    20  	nonce := sha256.New()
    21  	nonce.Write([]byte("nonce"))
    22  
    23  	cipherTextAndMac, err = Encrypt(nonce.Sum(nil), plainText, key.Sum(nil))
    24  	assert.NotEmpty(t, cipherTextAndMac)
    25  	assert.Nil(t, err)
    26  
    27  	cipherTextAndMac2, err := Encrypt(nonce.Sum(nil), []byte("cipherText"), key.Sum(nil))
    28  	assert.Equal(t, cipherTextAndMac, cipherTextAndMac2)
    29  
    30  	res, err := Decrypt(nonce.Sum(nil), cipherTextAndMac, key.Sum(nil))
    31  	assert.Nil(t, err)
    32  	assert.NotEmpty(t, res)
    33  	assert.Equal(t, plainText, res)
    34  
    35  	nonce.Write([]byte("key"))
    36  	res, err = Decrypt(nonce.Sum(nil), cipherTextAndMac, key.Sum(nil))
    37  	assert.NotNil(t, err)
    38  	assert.Empty(t, res)
    39  }
    40  
    41  func TestSeq(t *testing.T) {
    42  	key := sha256.New()
    43  	key.Write([]byte("1"))
    44  	plainText := []byte("3")
    45  
    46  	nonce := sha256.New()
    47  	nonce.Write([]byte("2"))
    48  
    49  	cipherTextAndMac, _ := Encrypt(nonce.Sum(nil), plainText, key.Sum(nil))
    50  	temp := make([]byte, 1)
    51  	temp[0] = 36
    52  	assert.Equal(t, cipherTextAndMac[:1], temp)
    53  }