Created
November 24, 2020 07:07
-
-
Save KaiserWerk/a8b6a0fe3a46f4c09f06cc9c9e3876b7 to your computer and use it in GitHub Desktop.
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
// inspired by https://gist.github.com/samuel/8b500ddd3f6118d052b5e6bc16bc4c09 | |
func generateSelfSignedCert(certPath string, keyPath string) { | |
// priv, err := rsa.GenerateKey(rand.Reader, *rsaBits) | |
priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) | |
if err != nil { | |
log.Fatal(err) | |
} | |
template := x509.Certificate{ | |
SerialNumber: big.NewInt(time.Now().UnixNano()), | |
Subject: pkix.Name{ | |
Organization: []string{"Localhost Ltd."}, | |
}, | |
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}, | |
NotBefore: time.Now(), | |
NotAfter: time.Now().Add(time.Hour * 24 * 180), | |
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, | |
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, | |
BasicConstraintsValid: true, | |
} | |
/* | |
hosts := strings.Split(*host, ",") | |
for _, h := range hosts { | |
if ip := net.ParseIP(h); ip != nil { | |
template.IPAddresses = append(template.IPAddresses, ip) | |
} else { | |
template.DNSNames = append(template.DNSNames, h) | |
} | |
} | |
if *isCA { | |
template.IsCA = true | |
template.KeyUsage |= x509.KeyUsageCertSign | |
} | |
*/ | |
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) | |
if err != nil { | |
log.Fatalf("Failed to create certificate: %s", err) | |
} | |
out := &bytes.Buffer{} | |
_ = pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) | |
_ = os.MkdirAll(filepath.Dir(keyPath), 0600) | |
_ = ioutil.WriteFile(certPath, out.Bytes(), 0600) | |
out.Reset() | |
_ = pem.Encode(out, pemBlockForKey(priv)) | |
_ = ioutil.WriteFile(keyPath, out.Bytes(), 0600) | |
} | |
func publicKey(priv interface{}) interface{} { | |
switch k := priv.(type) { | |
case *rsa.PrivateKey: | |
return &k.PublicKey | |
case *ecdsa.PrivateKey: | |
return &k.PublicKey | |
default: | |
return nil | |
} | |
} | |
func pemBlockForKey(priv interface{}) *pem.Block { | |
switch k := priv.(type) { | |
case *rsa.PrivateKey: | |
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} | |
case *ecdsa.PrivateKey: | |
b, err := x509.MarshalECPrivateKey(k) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err) | |
os.Exit(2) | |
} | |
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} | |
default: | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment