github.com/webdestroya/awsmocker@v0.2.6/internal/certgen/main.go (about) 1 //go:build generate 2 // +build generate 3 4 package main 5 6 import ( 7 "bytes" 8 "crypto/rand" 9 "crypto/rsa" 10 "crypto/x509" 11 "crypto/x509/pkix" 12 "encoding/pem" 13 "fmt" 14 "math/big" 15 "os" 16 "time" 17 ) 18 19 func main() { 20 21 // keep the key size low. we don't care about security here, this is a local mock server 22 caPrivKey, err := rsa.GenerateKey(rand.Reader, 2048) 23 if err != nil { 24 panic(err) 25 } 26 27 tpl := &x509.Certificate{ 28 SerialNumber: big.NewInt(1), 29 Subject: pkix.Name{ 30 CommonName: "AWSMocker Root CA", 31 Country: []string{"US"}, 32 Organization: []string{"webdestroya"}, 33 OrganizationalUnit: []string{"aws-mocker"}, 34 }, 35 NotBefore: time.Now(), 36 NotAfter: time.Now().AddDate(10, 0, 0), 37 IsCA: true, 38 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, 39 BasicConstraintsValid: true, 40 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, 41 } 42 43 caBytes, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &caPrivKey.PublicKey, caPrivKey) 44 if err != nil { 45 panic(err) 46 } 47 48 caPEM := new(bytes.Buffer) 49 pem.Encode(caPEM, &pem.Block{ 50 Type: "CERTIFICATE", 51 Bytes: caBytes, 52 }) 53 54 caPrivKeyPEM := new(bytes.Buffer) 55 pem.Encode(caPrivKeyPEM, &pem.Block{ 56 Type: "RSA PRIVATE KEY", 57 Bytes: x509.MarshalPKCS1PrivateKey(caPrivKey), 58 }) 59 60 if err := os.WriteFile("./cacert.pem", caPEM.Bytes(), 0o644); err != nil { 61 panic(fmt.Errorf("failed to write defaults file: %w", err)) 62 } 63 64 if err := os.WriteFile("./cakey.pem", caPrivKeyPEM.Bytes(), 0o644); err != nil { 65 panic(fmt.Errorf("failed to write defaults file: %w", err)) 66 } 67 68 }