chacha20_test.go 1.9 KB

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