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