chacha20_test.go 2.3 KB

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