Last active
October 17, 2025 13:34
-
-
Save Integralist/6aad6e8d1aade5674dbe6c63e089acb0 to your computer and use it in GitHub Desktop.
Go: generate Private Key and CSR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://go.dev/play/p/nDnCcCkMlFj | |
| package main | |
| import ( | |
| "crypto/ecdsa" | |
| "crypto/elliptic" | |
| "crypto/rand" | |
| "crypto/x509" | |
| "encoding/pem" | |
| "fmt" | |
| "log" | |
| ) | |
| func main() { | |
| var sanList = []string{"www.example.com", "api.example.com"} | |
| csr, cr, err := GenerateCSR(sanList) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| fmt.Printf("CSR:\n%s\n", csr) | |
| fmt.Printf("Certificate Request:\n%#v\n", cr) | |
| } | |
| // GenerateCSR creates the relevant items to produce a CSR. | |
| // NOTE: This can be replaced once in Elevation with calls to Fastly services. | |
| func GenerateCSR(sanList []string) ([]byte, *x509.CertificateRequest, error) { | |
| certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
| if err != nil { | |
| return nil, nil, fmt.Errorf("failed to generate private key for CSR: %w", err) | |
| } | |
| // WARNING: The following is for printing the private key. | |
| // It is for testing purposes only. | |
| privateKeyBytes, err := x509.MarshalECPrivateKey(certPrivateKey) | |
| if err != nil { | |
| return nil, nil, fmt.Errorf("failed to marshal private key for CSR: %w", err) | |
| } | |
| privateKeyPEM := pem.EncodeToMemory(&pem.Block{ | |
| Type: "EC PRIVATE KEY", | |
| Bytes: privateKeyBytes, | |
| }) | |
| fmt.Println("Private Key:") | |
| fmt.Println(string(privateKeyPEM)) | |
| dnsNames := make([]string, 0, len(sanList)) | |
| for _, san := range sanList { | |
| dnsNames = append(dnsNames, san) | |
| } | |
| csrTemplate := &x509.CertificateRequest{DNSNames: dnsNames} | |
| csrDER, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, certPrivateKey) | |
| if err != nil { | |
| return nil, nil, fmt.Errorf("error to creating CSR for '%#v': %w", dnsNames, err) | |
| } | |
| p := pem.EncodeToMemory(&pem.Block{ | |
| Type: "CERTIFICATE REQUEST", // Standard type for CSR PEM blocks | |
| Bytes: csrDER, // The DER-encoded CSR bytes | |
| }) | |
| csr, err := x509.ParseCertificateRequest(csrDER) | |
| if err != nil { | |
| return nil, nil, fmt.Errorf("failed to parse CSR for '%#v': %w", dnsNames, err) | |
| } | |
| return p, csr, nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment