github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/proxy/yuubinsya/crypto/handshake_test.go (about) 1 package crypto 2 3 import ( 4 "bytes" 5 "crypto" 6 "crypto/ecdh" 7 "crypto/ed25519" 8 "crypto/rand" 9 "crypto/sha256" 10 "fmt" 11 "io" 12 "testing" 13 14 "github.com/Asutorufa/yuhaiin/pkg/utils/assert" 15 "golang.org/x/crypto/chacha20poly1305" 16 "golang.org/x/crypto/hkdf" 17 ) 18 19 func TestEcdh(t *testing.T) { 20 c1, err := ecdh.P384().GenerateKey(rand.Reader) 21 assert.NoError(t, err) 22 c2, err := ecdh.P384().GenerateKey(rand.Reader) 23 assert.NoError(t, err) 24 25 p1 := c1.PublicKey().Bytes() 26 p2 := c2.PublicKey().Bytes() 27 28 pp1, err := ecdh.P384().NewPublicKey(p2) 29 assert.NoError(t, err) 30 pp2, err := ecdh.P384().NewPublicKey(p1) 31 assert.NoError(t, err) 32 33 cc1, err := c1.ECDH(pp1) 34 assert.NoError(t, err) 35 cc2, err := c2.ECDH(pp2) 36 assert.NoError(t, err) 37 38 t.Log(p1, p2, len(p1), len(p2)) 39 t.Log(cc1, cc2) 40 41 z := make([]byte, 32) 42 epk := ed25519.NewKeyFromSeed(z) 43 signature, err := epk.Sign(rand.Reader, cc1, crypto.Hash(0)) 44 assert.NoError(t, err) 45 46 t.Log(signature, len(signature)) 47 } 48 49 func TestChacha20(t *testing.T) { 50 a, err := chacha20poly1305.New(make([]byte, chacha20poly1305.KeySize)) 51 assert.NoError(t, err) 52 53 nouce := make([]byte, chacha20poly1305.NonceSize) 54 dst := make([]byte, 1024) 55 ret := a.Seal(dst[:0], nouce, []byte{1, 2}, nil) 56 57 t.Log(dst, ret) 58 59 } 60 61 func TestHkdf(t *testing.T) { 62 // Underlying hash function for HMAC. 63 hash := sha256.New 64 // Cryptographically secure master secret. 65 secret := []byte{0x00, 0x01, 0x02, 0x03} // i.e. NOT this. 66 // Non-secret salt, optional (can be nil). 67 // Recommended: hash-length random value. 68 salt := make([]byte, hash().Size()) 69 // if _, err := rand.Read(salt); err != nil { 70 // panic(err) 71 // } 72 // Non-secret context info, optional (can be nil). 73 info := []byte("hkdf example") 74 // Generate three 128-bit derived keys. 75 hkdf := hkdf.New(hash, secret, salt, info) 76 var keys [][]byte 77 for i := 0; i < 3; i++ { 78 key := make([]byte, 16) 79 if _, err := io.ReadFull(hkdf, key); err != nil { 80 panic(err) 81 } 82 keys = append(keys, key) 83 } 84 for i := range keys { 85 fmt.Printf("Key %v #%d: %v\n", keys[i], i+1, !bytes.Equal(keys[i], make([]byte, 16))) 86 } 87 // Output: 88 // Key #1: true 89 // Key #2: true 90 // Key #3: true 91 }