github.com/pion/dtls/v2@v2.2.12/examples/dial/verify/main.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 // Package main implements a DTLS client using a client certificate. 5 package main 6 7 import ( 8 "context" 9 "crypto/tls" 10 "crypto/x509" 11 "fmt" 12 "net" 13 "time" 14 15 "github.com/pion/dtls/v2" 16 "github.com/pion/dtls/v2/examples/util" 17 ) 18 19 func main() { 20 // Prepare the IP to connect to 21 addr := &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 4444} 22 23 // 24 // Everything below is the pion-DTLS API! Thanks for using it ❤️. 25 // 26 27 certificate, err := util.LoadKeyAndCertificate("examples/certificates/client.pem", 28 "examples/certificates/client.pub.pem") 29 util.Check(err) 30 31 rootCertificate, err := util.LoadCertificate("examples/certificates/server.pub.pem") 32 util.Check(err) 33 certPool := x509.NewCertPool() 34 cert, err := x509.ParseCertificate(rootCertificate.Certificate[0]) 35 util.Check(err) 36 certPool.AddCert(cert) 37 38 // Prepare the configuration of the DTLS connection 39 config := &dtls.Config{ 40 Certificates: []tls.Certificate{certificate}, 41 ExtendedMasterSecret: dtls.RequireExtendedMasterSecret, 42 RootCAs: certPool, 43 } 44 45 // Connect to a DTLS server 46 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 47 defer cancel() 48 dtlsConn, err := dtls.DialWithContext(ctx, "udp", addr, config) 49 util.Check(err) 50 defer func() { 51 util.Check(dtlsConn.Close()) 52 }() 53 54 fmt.Println("Connected; type 'exit' to shutdown gracefully") 55 56 // Simulate a chat session 57 util.Chat(dtlsConn) 58 }