github.com/quic-go/quic-go@v0.44.0/internal/handshake/hkdf_test.go (about) 1 package handshake 2 3 import ( 4 "crypto" 5 "crypto/cipher" 6 "crypto/tls" 7 "testing" 8 _ "unsafe" 9 10 "golang.org/x/exp/rand" 11 12 . "github.com/onsi/ginkgo/v2" 13 . "github.com/onsi/gomega" 14 ) 15 16 type cipherSuiteTLS13 struct { 17 ID uint16 18 KeyLen int 19 AEAD func(key, fixedNonce []byte) cipher.AEAD 20 Hash crypto.Hash 21 } 22 23 //go:linkname cipherSuiteTLS13ByID crypto/tls.cipherSuiteTLS13ByID 24 func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 25 26 //go:linkname expandLabel crypto/tls.(*cipherSuiteTLS13).expandLabel 27 func expandLabel(cs *cipherSuiteTLS13, secret []byte, label string, context []byte, length int) []byte 28 29 var _ = Describe("HKDF", func() { 30 DescribeTable("gets the same results as crypto/tls", 31 func(cipherSuite uint16, secret, context []byte, label string, length int) { 32 cs := cipherSuiteTLS13ByID(cipherSuite) 33 expected := expandLabel(cs, secret, label, context, length) 34 expanded := hkdfExpandLabel(cs.Hash, secret, context, label, length) 35 Expect(expanded).To(Equal(expected)) 36 }, 37 Entry("TLS_AES_128_GCM_SHA256", tls.TLS_AES_128_GCM_SHA256, []byte("secret"), []byte("context"), "label", 42), 38 Entry("TLS_AES_256_GCM_SHA384", tls.TLS_AES_256_GCM_SHA384, []byte("secret"), []byte("context"), "label", 100), 39 Entry("TLS_CHACHA20_POLY1305_SHA256", tls.TLS_CHACHA20_POLY1305_SHA256, []byte("secret"), []byte("context"), "label", 77), 40 ) 41 }) 42 43 func BenchmarkHKDFExpandLabelStandardLibrary(b *testing.B) { 44 b.Run("TLS_AES_128_GCM_SHA256", func(b *testing.B) { benchmarkHKDFExpandLabel(b, tls.TLS_AES_128_GCM_SHA256, true) }) 45 b.Run("TLS_AES_256_GCM_SHA384", func(b *testing.B) { benchmarkHKDFExpandLabel(b, tls.TLS_AES_256_GCM_SHA384, true) }) 46 b.Run("TLS_CHACHA20_POLY1305_SHA256", func(b *testing.B) { benchmarkHKDFExpandLabel(b, tls.TLS_CHACHA20_POLY1305_SHA256, true) }) 47 } 48 49 func BenchmarkHKDFExpandLabelOptimized(b *testing.B) { 50 b.Run("TLS_AES_128_GCM_SHA256", func(b *testing.B) { benchmarkHKDFExpandLabel(b, tls.TLS_AES_128_GCM_SHA256, false) }) 51 b.Run("TLS_AES_256_GCM_SHA384", func(b *testing.B) { benchmarkHKDFExpandLabel(b, tls.TLS_AES_256_GCM_SHA384, false) }) 52 b.Run("TLS_CHACHA20_POLY1305_SHA256", func(b *testing.B) { benchmarkHKDFExpandLabel(b, tls.TLS_CHACHA20_POLY1305_SHA256, false) }) 53 } 54 55 func benchmarkHKDFExpandLabel(b *testing.B, cipherSuite uint16, useStdLib bool) { 56 b.ReportAllocs() 57 cs := cipherSuiteTLS13ByID(cipherSuite) 58 secret := make([]byte, 32) 59 rand.Read(secret) 60 b.ResetTimer() 61 for i := 0; i < b.N; i++ { 62 if useStdLib { 63 expandLabel(cs, secret, "label", []byte("context"), 42) 64 } else { 65 hkdfExpandLabel(cs.Hash, secret, []byte("context"), "label", 42) 66 } 67 } 68 }