Skip to content

Instantly share code, notes, and snippets.

@omerkaya1
Created April 19, 2024 08:43
Show Gist options
  • Save omerkaya1/942802b2ebe36611cac8477c97158b36 to your computer and use it in GitHub Desktop.
Save omerkaya1/942802b2ebe36611cac8477c97158b36 to your computer and use it in GitHub Desktop.
Create TLS certs (mostly for unit tests)
package some_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"
)
func composeCerts() ([]byte, []byte, []byte, error) {
// Create a CA certificate
caTemplate := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "CA"},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
caKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, nil, nil, err
}
caCertDER, err := x509.CreateCertificate(rand.Reader, &caTemplate, &caTemplate, &caKey.PublicKey, caKey)
if err != nil {
return nil, nil, nil, err
}
ca := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCertDER})
// Create a user certificate
userTemplate := x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{CommonName: "User"},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0), // Valid for 1 year
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
}
userKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, nil, nil, err
}
userCertDER, err := x509.CreateCertificate(rand.Reader, &userTemplate, &caTemplate, &userKey.PublicKey, caKey)
if err != nil {
return nil, nil, nil, err
}
user := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: userCertDER})
// Write user private key to file
privBytes, err := x509.MarshalECPrivateKey(userKey)
if err != nil {
fmt.Println("Error marshaling user private key:", err)
return nil, nil, nil, err
}
key := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes})
return ca, user, key, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment