chacha20_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package crypto_test
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "testing"
  6. . "v2ray.com/core/common/crypto"
  7. "v2ray.com/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. assert := assert.On(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. }
  53. func TestChaCha20Decoding(t *testing.T) {
  54. assert := assert.On(t)
  55. key := make([]byte, 32)
  56. rand.Read(key)
  57. iv := make([]byte, 8)
  58. rand.Read(iv)
  59. stream := NewChaCha20Stream(key, iv)
  60. payload := make([]byte, 1024)
  61. rand.Read(payload)
  62. x := make([]byte, len(payload))
  63. stream.XORKeyStream(x, payload)
  64. stream2 := NewChaCha20Stream(key, iv)
  65. stream2.XORKeyStream(x, x)
  66. assert.Bytes(x).Equals(payload)
  67. }