decryptionreader_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package vmess
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/rand"
  6. mrand "math/rand"
  7. "testing"
  8. )
  9. func randomBytes(p []byte, t *testing.T) {
  10. nBytes, err := rand.Read(p)
  11. if err != nil {
  12. t.Fatal(err)
  13. }
  14. if nBytes != len(p) {
  15. t.Error("Unable to generate %d bytes of random buffer", len(p))
  16. }
  17. }
  18. func TestNormalReading(t *testing.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. cipher, err := aes.NewCipher(key)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. ciphertext := make([]byte, testSize)
  30. for encryptSize := 0; encryptSize < testSize; encryptSize += blockSize {
  31. cipher.Encrypt(ciphertext[encryptSize:], plaintext[encryptSize:])
  32. }
  33. ciphertextcopy := make([]byte, testSize)
  34. copy(ciphertextcopy, ciphertext)
  35. reader, err := NewDecryptionReader(bytes.NewReader(ciphertextcopy), key)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. readtext := make([]byte, testSize)
  40. readSize := 0
  41. for readSize < testSize {
  42. nBytes := mrand.Intn(16) + 1
  43. if nBytes > testSize-readSize {
  44. nBytes = testSize - readSize
  45. }
  46. bytesRead, err := reader.Read(readtext[readSize : readSize+nBytes])
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. if bytesRead != nBytes {
  51. t.Errorf("Expected to read %d bytes, but only read %d bytes", nBytes, bytesRead)
  52. }
  53. readSize += nBytes
  54. }
  55. if !bytes.Equal(readtext, plaintext) {
  56. t.Errorf("Expected plaintext %v, but got %v", plaintext, readtext)
  57. }
  58. }