github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/encrypt/obscure/obscure_test.go (about)

     1  package obscure
     2  
     3  import (
     4  	cryptorand "crypto/rand"
     5  	mathrand "math/rand"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestObscure_Reproducible(t *testing.T) {
    12  	key := "hello world"
    13  	obs1 := New([]byte(key))
    14  	obs2 := New([]byte(key))
    15  	assert.Equal(t, obs1.Index(), obs2.Index())
    16  
    17  	table1 := obs1.Table()
    18  	table2 := obs2.Table()
    19  	for i := 0; i < idxLen; i++ {
    20  		assert.Equal(t, table1[i], table2[i])
    21  	}
    22  }
    23  
    24  func TestObscure(t *testing.T) {
    25  	key := "hello world"
    26  	obs := New([]byte(key))
    27  
    28  	encoded := obs.EncodeToBytes([]byte(key))
    29  	decoded, err := obs.DecodeBytes(encoded)
    30  	assert.Nil(t, err)
    31  	assert.Equal(t, key, string(decoded))
    32  }
    33  
    34  func TestObscure_ZeroLengthInput(t *testing.T) {
    35  	key := []byte{248, 77, 8, 37, 138, 1, 232, 104, 31}
    36  	obs := New(key)
    37  	data := []byte{}
    38  	encoded := obs.EncodeToString(data)
    39  	decoded, err := obs.DecodeString(encoded)
    40  	assert.Nil(t, err)
    41  	assert.Nil(t, decoded)
    42  }
    43  
    44  func TestObscure_RandomBytes(t *testing.T) {
    45  	for i := 0; i < 1000; i++ {
    46  		key := make([]byte, mathrand.Intn(100))
    47  		_, _ = cryptorand.Read(key)
    48  		obs := New(key)
    49  
    50  		data := make([]byte, 1000)
    51  		for j := 0; j < 1000; j++ {
    52  			data = data[:mathrand.Intn(1000)]
    53  			_, _ = cryptorand.Read(data)
    54  			encoded := obs.EncodeToString(data)
    55  			decoded, err := obs.DecodeString(encoded)
    56  			assert.Nil(t, err)
    57  			if len(data) == 0 {
    58  				assert.Nil(t, decoded)
    59  			} else {
    60  				assert.Equal(t, data, decoded)
    61  			}
    62  		}
    63  	}
    64  }