GenerateTLSConfig generates a TLS configuration with a self-signed certificate
(opts TLSConfigOptions)
| 21 | |
| 22 | // GenerateTLSConfig generates a TLS configuration with a self-signed certificate |
| 23 | func GenerateTLSConfig(opts TLSConfigOptions) (*tls.Config, error) { |
| 24 | // Generate private key |
| 25 | key, err := rsa.GenerateKey(rand.Reader, TLSKeyBits) |
| 26 | if err != nil { |
| 27 | return nil, fmt.Errorf("failed to generate private key: %w", err) |
| 28 | } |
| 29 | |
| 30 | // Set default values |
| 31 | if opts.Organization == "" { |
| 32 | opts.Organization = "QUIC Server" |
| 33 | } |
| 34 | if len(opts.IPAddresses) == 0 { |
| 35 | opts.IPAddresses = []net.IP{net.IPv4(127, 0, 0, 1)} |
| 36 | } |
| 37 | |
| 38 | // Create certificate template |
| 39 | template := x509.Certificate{ |
| 40 | SerialNumber: big.NewInt(1), |
| 41 | Subject: pkix.Name{ |
| 42 | Organization: []string{opts.Organization}, |
| 43 | }, |
| 44 | NotBefore: time.Now(), |
| 45 | NotAfter: time.Now().Add(CertValidityPeriod), |
| 46 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, |
| 47 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 48 | IPAddresses: opts.IPAddresses, |
| 49 | DNSNames: opts.DNSNames, |
| 50 | } |
| 51 | |
| 52 | // Generate certificate |
| 53 | certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) |
| 54 | if err != nil { |
| 55 | return nil, fmt.Errorf("failed to create certificate: %w", err) |
| 56 | } |
| 57 | |
| 58 | // Create TLS certificate |
| 59 | cert := tls.Certificate{ |
| 60 | Certificate: [][]byte{certDER}, |
| 61 | PrivateKey: key, |
| 62 | } |
| 63 | |
| 64 | return &tls.Config{ |
| 65 | Certificates: []tls.Certificate{cert}, |
| 66 | NextProtos: []string{"h3"}, |
| 67 | }, nil |
| 68 | } |