GetTLSConfigs generates TLS configurations for a test server and client that trust each other using an in-memory certificate authority.
()
| 20 | // GetTLSConfigs generates TLS configurations for a test server and client that |
| 21 | // trust each other using an in-memory certificate authority. |
| 22 | func GetTLSConfigs() (serverTLSConf, clientTLSConf *tls.Config, err error) { //nolint:nonamedreturns // gocritic unnamedResult prefers naming server and client TLS configurations along with the error |
| 23 | // set up our CA certificate |
| 24 | ca := &x509.Certificate{ |
| 25 | SerialNumber: big.NewInt(2021), |
| 26 | Subject: pkix.Name{ |
| 27 | Organization: []string{"Fiber"}, |
| 28 | Country: []string{"NL"}, |
| 29 | Province: []string{""}, |
| 30 | Locality: []string{"Amsterdam"}, |
| 31 | StreetAddress: []string{"Huidenstraat"}, |
| 32 | PostalCode: []string{"1011 AA"}, |
| 33 | }, |
| 34 | NotBefore: time.Now(), |
| 35 | NotAfter: time.Now().AddDate(10, 0, 0), |
| 36 | IsCA: true, |
| 37 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, |
| 38 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, |
| 39 | BasicConstraintsValid: true, |
| 40 | } |
| 41 | |
| 42 | // create our private and public key |
| 43 | caPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096) |
| 44 | if err != nil { |
| 45 | return nil, nil, fmt.Errorf("generate CA key: %w", err) |
| 46 | } |
| 47 | |
| 48 | // create the CA |
| 49 | caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &caPrivateKey.PublicKey, caPrivateKey) |
| 50 | if err != nil { |
| 51 | return nil, nil, fmt.Errorf("create CA certificate: %w", err) |
| 52 | } |
| 53 | |
| 54 | // pem encode |
| 55 | var caPEM bytes.Buffer |
| 56 | if err = pem.Encode(&caPEM, &pem.Block{ |
| 57 | Type: "CERTIFICATE", |
| 58 | Bytes: caBytes, |
| 59 | }); err != nil { |
| 60 | return nil, nil, fmt.Errorf("encode CA cert: %w", err) |
| 61 | } |
| 62 | |
| 63 | var caPrivKeyPEM bytes.Buffer |
| 64 | if err = pem.Encode(&caPrivKeyPEM, &pem.Block{ |
| 65 | Type: "RSA PRIVATE KEY", |
| 66 | Bytes: x509.MarshalPKCS1PrivateKey(caPrivateKey), |
| 67 | }); err != nil { |
| 68 | return nil, nil, fmt.Errorf("encode CA private key: %w", err) |
| 69 | } |
| 70 | |
| 71 | // set up our server certificate |
| 72 | cert := &x509.Certificate{ |
| 73 | SerialNumber: big.NewInt(2021), |
| 74 | Subject: pkix.Name{ |
| 75 | Organization: []string{"Fiber"}, |
| 76 | Country: []string{"NL"}, |
| 77 | Province: []string{""}, |
| 78 | Locality: []string{"Amsterdam"}, |
| 79 | StreetAddress: []string{"Huidenstraat"}, |