Skip to content

Instantly share code, notes, and snippets.

@noamt
Created February 18, 2020 16:15
Show Gist options
  • Save noamt/2697daad9527027f141267788b26abea to your computer and use it in GitHub Desktop.
Save noamt/2697daad9527027f141267788b26abea to your computer and use it in GitHub Desktop.
For blog post "Simulating SSL outages with Go"
func expiredSSLCertificate() (*tls.Certificate, error) {
priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return nil, fmt.Errorf("failed to generate private key: %w", err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add( -time.Hour * 1), // time to expire
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1"))
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, fmt.Errorf("failed to create certificate: %w", err)
}
certBuffer := &bytes.Buffer{}
if err = pem.Encode(certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return nil, fmt.Errorf("failed to encode certificate: %w", err)
}
b, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return nil, fmt.Errorf("failed to marshal ECDSA private key: %w", err)
}
keyBuffer := &bytes.Buffer{}
if err := pem.Encode(keyBuffer, &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}); err != nil {
return nil, fmt.Errorf("failed to encode private key: %w", err)
}
certificate, err := tls.X509KeyPair(certBuffer.Bytes(), keyBuffer.Bytes())
if err != nil {
return nil, fmt.Errorf("failed to create certificate: %w", err)
}
return &certificate, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment