github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/storage/encrypt_test.go (about)

     1  package storage
     2  
     3  import (
     4  	"encoding/json"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"github.com/stretchr/testify/require"
     9  	"k8s.io/apimachinery/pkg/util/rand"
    10  )
    11  
    12  func TestNewEncrypter(t *testing.T) {
    13  
    14  	type testDto struct {
    15  		Data string `json:"data"`
    16  	}
    17  
    18  	t.Run("success json", func(t *testing.T) {
    19  		secretKey := rand.String(32)
    20  
    21  		e := NewEncrypter(secretKey)
    22  		dto := testDto{
    23  			Data: secretKey,
    24  		}
    25  
    26  		j, err := json.Marshal(&dto)
    27  		require.NoError(t, err)
    28  
    29  		enc, err := e.Encrypt(j)
    30  		require.NoError(t, err)
    31  		assert.NotEqual(t, j, enc)
    32  
    33  		enc, err = e.Decrypt(enc)
    34  		require.NoError(t, err)
    35  		assert.Equal(t, j, enc)
    36  
    37  		err = json.Unmarshal(enc, &dto)
    38  		require.NoError(t, err)
    39  	})
    40  
    41  	t.Run("success string", func(t *testing.T) {
    42  		secretKey := rand.String(32)
    43  
    44  		e := NewEncrypter(secretKey)
    45  		dto := []byte("test")
    46  
    47  		enc, err := e.Encrypt(dto)
    48  		require.NoError(t, err)
    49  		assert.NotEqual(t, dto, enc)
    50  
    51  		enc, err = e.Decrypt(enc)
    52  		require.NoError(t, err)
    53  		assert.Equal(t, dto, enc)
    54  	})
    55  
    56  	t.Run("wrong key", func(t *testing.T) {
    57  		secretKey := ""
    58  
    59  		e := NewEncrypter(secretKey)
    60  
    61  		dto := testDto{
    62  			Data: secretKey,
    63  		}
    64  
    65  		j, err := json.Marshal(&dto)
    66  		require.NoError(t, err)
    67  
    68  		_, err = e.Encrypt(j)
    69  		require.Error(t, err)
    70  	})
    71  
    72  }