2015-09-08 09:39:32 -04:00
|
|
|
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-08 09:39:32 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func randomBytes(p []byte, t *testing.T) {
|
2015-09-08 09:39:49 -04:00
|
|
|
nBytes, err := rand.Read(p)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if nBytes != len(p) {
|
|
|
|
t.Error("Unable to generate %d bytes of random buffer", len(p))
|
|
|
|
}
|
2015-09-08 09:39:32 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestNormalReading(t *testing.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-08 09:39:49 -04:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
2015-09-08 12:21:33 -04:00
|
|
|
aesMode := cipher.NewCBCEncrypter(aesBlock, iv)
|
2015-09-08 09:39:49 -04:00
|
|
|
|
|
|
|
ciphertext := make([]byte, testSize)
|
2015-09-08 12:21:33 -04:00
|
|
|
aesMode.CryptBlocks(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-08 09:39:49 -04:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
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])
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if bytesRead != nBytes {
|
|
|
|
t.Errorf("Expected to read %d bytes, but only read %d bytes", nBytes, bytesRead)
|
|
|
|
}
|
|
|
|
readSize += nBytes
|
|
|
|
}
|
|
|
|
if !bytes.Equal(readtext, plaintext) {
|
|
|
|
t.Errorf("Expected plaintext %v, but got %v", plaintext, readtext)
|
|
|
|
}
|
|
|
|
}
|