chacha20_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package crypto_test
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "testing"
  6. "v2ray.com/core/common"
  7. . "v2ray.com/core/common/crypto"
  8. . "v2ray.com/ext/assert"
  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. assert := With(t)
  17. var cases = []struct {
  18. key []byte
  19. iv []byte
  20. output []byte
  21. }{
  22. {
  23. key: mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000000"),
  24. iv: mustDecodeHex("0000000000000000"),
  25. output: mustDecodeHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7" +
  26. "da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586" +
  27. "9f07e7be5551387a98ba977c732d080dcb0f29a048e3656912c6533e32ee7aed" +
  28. "29b721769ce64e43d57133b074d839d531ed1f28510afb45ace10a1f4b794d6f"),
  29. },
  30. {
  31. key: mustDecodeHex("5555555555555555555555555555555555555555555555555555555555555555"),
  32. iv: mustDecodeHex("5555555555555555"),
  33. output: mustDecodeHex("bea9411aa453c5434a5ae8c92862f564396855a9ea6e22d6d3b50ae1b3663311" +
  34. "a4a3606c671d605ce16c3aece8e61ea145c59775017bee2fa6f88afc758069f7" +
  35. "e0b8f676e644216f4d2a3422d7fa36c6c4931aca950e9da42788e6d0b6d1cd83" +
  36. "8ef652e97b145b14871eae6c6804c7004db5ac2fce4c68c726d004b10fcaba86"),
  37. },
  38. {
  39. key: mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000000"),
  40. iv: mustDecodeHex("000000000000000000000000"),
  41. output: mustDecodeHex("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"),
  42. },
  43. }
  44. for _, c := range cases {
  45. s := NewChaCha20Stream(c.key, c.iv)
  46. input := make([]byte, len(c.output))
  47. actualOutout := make([]byte, len(c.output))
  48. s.XORKeyStream(actualOutout, input)
  49. assert(c.output, Equals, actualOutout)
  50. }
  51. }
  52. func TestChaCha20Decoding(t *testing.T) {
  53. assert := With(t)
  54. key := make([]byte, 32)
  55. rand.Read(key)
  56. iv := make([]byte, 8)
  57. rand.Read(iv)
  58. stream := NewChaCha20Stream(key, iv)
  59. payload := make([]byte, 1024)
  60. 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. assert(x, Equals, payload)
  66. }