-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrandctr_test.go
61 lines (55 loc) · 1.44 KB
/
randctr_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package enigma
import (
"crypto/aes"
"crypto/cipher"
cryptoRand "crypto/rand"
"encoding/binary"
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRandCTR(t *testing.T) {
assert := assert.New(t)
var err error
dataSize := int(1 << 20)
sampleTimes := int(1 << 10)
bufSize := int(1 << 16)
r := cryptoRand.Reader
// Construct the referential data for testing.
plain := make([]byte, dataSize)
_, err = r.Read(plain)
assert.NoError(err)
key := make([]byte, 32) // AES-256
_, err = r.Read(key)
assert.NoError(err)
iv := make([]byte, aes.BlockSize)
_, err = r.Read(iv)
assert.NoError(err)
block, err := aes.NewCipher(key)
assert.NoError(err)
ctrStream := cipher.NewCTR(block, iv)
cipher := make([]byte, dataSize)
ctrStream.XORKeyStream(cipher, plain)
// Create our random stream for testing.
randCTRStream := newRandCTR(block, iv)
// Randomly choose some data range and perform testing.
var seedBuf [8]byte
_, err = r.Read(seedBuf[:])
assert.NoError(err)
src := rand.NewSource(int64(binary.LittleEndian.Uint64(seedBuf[:])))
rand := rand.New(src)
buf := make([]byte, bufSize)
for i := 0; i < sampleTimes; i++ {
start := rand.Intn(dataSize)
size := rand.Intn(len(buf))
end := start + size
if end > dataSize {
end = dataSize
size = dataSize - start
}
dst := buf[:size]
randCTRStream.Seek(uint64(start))
randCTRStream.XORKeyStream(dst, plain[start:end])
assert.Equal(dst, cipher[start:end])
}
}