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