chacha20_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package crypto_test
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "testing"
  6. . "github.com/v2ray/v2ray-core/common/crypto"
  7. v2testing "github.com/v2ray/v2ray-core/testing"
  8. "github.com/v2ray/v2ray-core/testing/assert"
  9. )
  10. func mustDecodeHex(s string) []byte {
  11. b, err := hex.DecodeString(s)
  12. if err != nil {
  13. panic(err)
  14. }
  15. return b
  16. }
  17. func TestChaCha20Stream(t *testing.T) {
  18. v2testing.Current(t)
  19. var cases = []struct {
  20. key []byte
  21. iv []byte
  22. output []byte
  23. }{
  24. {
  25. key: mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000000"),
  26. iv: mustDecodeHex("0000000000000000"),
  27. output: mustDecodeHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" +
  28. "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586" +
  29. "9f07e7be5551387a98ba977c732d080dcb0f29a048e3656912c6533e32ee7aed" +
  30. "29b721769ce64e43d57133b074d839d531ed1f28510afb45ace10a1f4b794d6f"),
  31. },
  32. {
  33. key: mustDecodeHex("5555555555555555555555555555555555555555555555555555555555555555"),
  34. iv: mustDecodeHex("5555555555555555"),
  35. output: mustDecodeHex("bea9411aa453c5434a5ae8c92862f564396855a9ea6e22d6d3b50ae1b3663311" +
  36. "a4a3606c671d605ce16c3aece8e61ea145c59775017bee2fa6f88afc758069f7" +
  37. "e0b8f676e644216f4d2a3422d7fa36c6c4931aca950e9da42788e6d0b6d1cd83" +
  38. "8ef652e97b145b14871eae6c6804c7004db5ac2fce4c68c726d004b10fcaba86"),
  39. },
  40. {
  41. key: mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000000"),
  42. iv: mustDecodeHex("000000000000000000000000"),
  43. output: mustDecodeHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"),
  44. },
  45. }
  46. for _, c := range cases {
  47. s := NewChaCha20Stream(c.key, c.iv)
  48. input := make([]byte, len(c.output))
  49. actualOutout := make([]byte, len(c.output))
  50. s.XORKeyStream(actualOutout, input)
  51. assert.Bytes(c.output).Equals(actualOutout)
  52. }
  53. }
  54. func TestChaCha20Decoding(t *testing.T) {
  55. v2testing.Current(t)
  56. key := make([]byte, 32)
  57. rand.Read(key)
  58. iv := make([]byte, 8)
  59. rand.Read(iv)
  60. stream := NewChaCha20Stream(key, iv)
  61. payload := make([]byte, 1024)
  62. rand.Read(payload)
  63. x := make([]byte, len(payload))
  64. stream.XORKeyStream(x, payload)
  65. stream2 := NewChaCha20Stream(key, iv)
  66. stream2.XORKeyStream(x, x)
  67. assert.Bytes(x).Equals(payload)
  68. }