decryptionreader_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package vmess
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. mrand "math/rand"
  8. "testing"
  9. "github.com/v2ray/v2ray-core/testing/unit"
  10. )
  11. func randomBytes(p []byte, t *testing.T) {
  12. assert := unit.Assert(t)
  13. nBytes, err := rand.Read(p)
  14. assert.Error(err).IsNil()
  15. assert.Int(nBytes).Named("# bytes of random buffer").Equals(len(p))
  16. }
  17. func TestNormalReading(t *testing.T) {
  18. assert := unit.Assert(t)
  19. testSize := 256
  20. plaintext := make([]byte, testSize)
  21. randomBytes(plaintext, t)
  22. keySize := 16
  23. key := make([]byte, keySize)
  24. randomBytes(key, t)
  25. iv := make([]byte, keySize)
  26. randomBytes(iv, t)
  27. aesBlock, err := aes.NewCipher(key)
  28. assert.Error(err).IsNil()
  29. aesStream := cipher.NewCFBEncrypter(aesBlock, iv)
  30. ciphertext := make([]byte, testSize)
  31. aesStream.XORKeyStream(ciphertext, plaintext)
  32. ciphertextcopy := make([]byte, testSize)
  33. copy(ciphertextcopy, ciphertext)
  34. reader, err := NewDecryptionReader(bytes.NewReader(ciphertextcopy), key, iv)
  35. assert.Error(err).IsNil()
  36. readtext := make([]byte, testSize)
  37. readSize := 0
  38. for readSize < testSize {
  39. nBytes := mrand.Intn(16) + 1
  40. if nBytes > testSize-readSize {
  41. nBytes = testSize - readSize
  42. }
  43. bytesRead, err := reader.Read(readtext[readSize : readSize+nBytes])
  44. assert.Error(err).IsNil()
  45. assert.Int(bytesRead).Equals(nBytes)
  46. readSize += nBytes
  47. }
  48. assert.Bytes(readtext).Named("Plaintext").Equals(plaintext)
  49. }