Skip to content

Instantly share code, notes, and snippets.

@kevin-cantwell
Last active February 26, 2019 14:56
Show Gist options
  • Save kevin-cantwell/74aa64abf5feecc381298519f90c48ee to your computer and use it in GitHub Desktop.
Save kevin-cantwell/74aa64abf5feecc381298519f90c48ee to your computer and use it in GitHub Desktop.
generate a localhost tls config
// returns an ad-hoc tls config that does not need to write or read any files.
func tlsConfig() *tls.Config {
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
panic(err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"My Company"},
},
IPAddresses: []net.IP{[]byte{127, 0, 0, 1}},
DNSNames: []string{"localhost"},
IsCA: true,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv)
if err != nil {
panic(err)
}
var cert bytes.Buffer
if err := pem.Encode(&cert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
panic(err)
}
var key bytes.Buffer
if err := pem.Encode(&key, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
panic(err)
}
return &tls.Config{
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
c, err := tls.X509KeyPair(cert.Bytes(), key.Bytes())
if err != nil {
return nil, err
}
return &c, nil
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment