decryptionreader_test.go 1.5 KB

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