1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-06 17:36:40 -05:00
v2fly/io/vmess/decryptionreader_test.go

63 lines
1.4 KiB
Go
Raw Normal View History

package vmess
import (
2015-09-08 09:39:49 -04:00
"bytes"
"crypto/aes"
2015-09-08 12:21:33 -04:00
"crypto/cipher"
2015-09-08 09:39:49 -04:00
"crypto/rand"
mrand "math/rand"
"testing"
2015-09-09 09:26:11 -04:00
"github.com/v2ray/v2ray-core/testing/unit"
)
func randomBytes(p []byte, t *testing.T) {
2015-09-09 09:26:11 -04:00
assert := unit.Assert(t)
2015-09-08 09:39:49 -04:00
nBytes, err := rand.Read(p)
2015-09-09 09:26:11 -04:00
assert.Error(err).IsNil()
assert.Int(nBytes).Named("# bytes of random buffer").Equals(len(p))
}
func TestNormalReading(t *testing.T) {
2015-09-09 09:26:11 -04:00
assert := unit.Assert(t)
2015-09-08 09:39:49 -04:00
testSize := 256
plaintext := make([]byte, testSize)
randomBytes(plaintext, t)
keySize := 16
key := make([]byte, keySize)
randomBytes(key, t)
2015-09-08 12:21:33 -04:00
iv := make([]byte, keySize)
randomBytes(iv, t)
2015-09-08 09:39:49 -04:00
2015-09-08 12:21:15 -04:00
aesBlock, err := aes.NewCipher(key)
2015-09-09 09:26:11 -04:00
assert.Error(err).IsNil()
2015-09-12 14:36:21 -04:00
aesStream := cipher.NewCFBEncrypter(aesBlock, iv)
2015-09-08 09:39:49 -04:00
ciphertext := make([]byte, testSize)
2015-09-12 14:36:21 -04:00
aesStream.XORKeyStream(ciphertext, plaintext)
2015-09-08 09:39:49 -04:00
ciphertextcopy := make([]byte, testSize)
copy(ciphertextcopy, ciphertext)
2015-09-08 12:21:15 -04:00
reader, err := NewDecryptionReader(bytes.NewReader(ciphertextcopy), key, iv)
2015-09-09 09:18:29 -04:00
assert.Error(err).IsNil()
2015-09-08 09:39:49 -04:00
readtext := make([]byte, testSize)
readSize := 0
for readSize < testSize {
nBytes := mrand.Intn(16) + 1
if nBytes > testSize-readSize {
nBytes = testSize - readSize
}
bytesRead, err := reader.Read(readtext[readSize : readSize+nBytes])
2015-09-09 09:18:29 -04:00
assert.Error(err).IsNil()
2015-09-09 09:26:11 -04:00
assert.Int(bytesRead).Equals(nBytes)
2015-09-08 09:39:49 -04:00
readSize += nBytes
}
2015-09-09 09:26:11 -04:00
assert.Bytes(readtext).Named("Plaintext").Equals(plaintext)
2015-09-08 09:39:49 -04:00
}