Skip to content

Instantly share code, notes, and snippets.

@kaimingguo
Created February 6, 2025 01:53
Show Gist options
  • Save kaimingguo/cd51534cbae576c9704c3abf7a982825 to your computer and use it in GitHub Desktop.
Save kaimingguo/cd51534cbae576c9704c3abf7a982825 to your computer and use it in GitHub Desktop.
Self-signed certificate in Go
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/pem"
"fmt"
"math/big"
"os"
"time"
)
func main() {
// Load private key
keyBytes, err := os.ReadFile("server.key")
if err != nil {
panic(err)
}
// Decode PEM private key
keyBlock, _ := pem.Decode(keyBytes)
if keyBlock == nil {
panic(fmt.Errorf("Failed to decode PEM private key"))
}
privateKey, err := parsePrivateKey(keyBlock.Bytes)
if err != nil {
panic(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: "localhost",
Country: []string{"TW"},
Province: []string{"Taiwan"},
Locality: []string{"Taipei"},
Organization: []string{"Work"},
OrganizationalUnit: []string{"Unknown"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
BasicConstraintsValid: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{"localhost"},
}
derBytes, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
Subject: template.Subject,
DNSNames: template.DNSNames,
SignatureAlgorithm: x509.SHA256WithRSA,
}, privateKey)
if err != nil {
panic(err)
}
csrBytes := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: derBytes,
})
fmt.Println(base64.StdEncoding.EncodeToString(csrBytes))
}
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
return key, nil
}
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
switch key := key.(type) {
case *rsa.PrivateKey, *ecdsa.PrivateKey:
return key, nil
default:
return nil, fmt.Errorf("Found unknown private key type in PKCS#8 wrapping")
}
}
if key, err := x509.ParseECPrivateKey(der); err == nil {
return key, nil
}
return nil, fmt.Errorf("Failed to parse private key")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment