From c12e24244a4b2cd171fb010f2b6c6a8b5aabb876 Mon Sep 17 00:00:00 2001 From: Martin Tournoij Date: Tue, 27 Oct 2020 19:34:17 +0800 Subject: [PATCH] Don't overwrite the -key-file if it's identical to -cert-file (#264) Especially for testing I find it much more convenient to just store both the key and certificate in a single file, which works with pretty much all software I've used. Currently, the -cert-file will overwrite the -key-file since it uses ioutil.WriteFile(). This fixes it to *append* if the files are identical. Co-authored-by: Filippo Valsorda --- cert.go | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/cert.go b/cert.go index 77b2ee0..34e9e80 100644 --- a/cert.go +++ b/cert.go @@ -108,15 +108,20 @@ func (m *mkcert) makeCert(hosts []string) { certFile, keyFile, p12File := m.fileNames(hosts) if !m.pkcs12 { + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}) privDER, err := x509.MarshalPKCS8PrivateKey(priv) fatalIfErr(err, "failed to encode certificate key") - err = ioutil.WriteFile(keyFile, pem.EncodeToMemory( - &pem.Block{Type: "PRIVATE KEY", Bytes: privDER}), 0600) - fatalIfErr(err, "failed to save certificate key") + privPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privDER}) - err = ioutil.WriteFile(certFile, pem.EncodeToMemory( - &pem.Block{Type: "CERTIFICATE", Bytes: cert}), 0644) - fatalIfErr(err, "failed to save certificate") + if certFile == keyFile { + err = ioutil.WriteFile(keyFile, append(certPEM, privPEM...), 0600) + fatalIfErr(err, "failed to save certificate and key") + } else { + err = ioutil.WriteFile(certFile, certPEM, 0644) + fatalIfErr(err, "failed to save certificate") + err = ioutil.WriteFile(keyFile, privPEM, 0600) + fatalIfErr(err, "failed to save certificate key") + } } else { domainCert, _ := x509.ParseCertificate(cert) pfxData, err := pkcs12.Encode(rand.Reader, priv, domainCert, []*x509.Certificate{m.caCert}, "changeit") @@ -128,7 +133,11 @@ func (m *mkcert) makeCert(hosts []string) { m.printHosts(hosts) if !m.pkcs12 { - log.Printf("\nThe certificate is at \"%s\" and the key at \"%s\" ✅\n\n", certFile, keyFile) + if certFile == keyFile { + log.Printf("\nThe certificate and key are at \"%s\" ✅\n\n", certFile) + } else { + log.Printf("\nThe certificate is at \"%s\" and the key at \"%s\" ✅\n\n", certFile, keyFile) + } } else { log.Printf("\nThe PKCS#12 bundle is at \"%s\" ✅\n", p12File) log.Printf("\nThe legacy PKCS#12 encryption password is the often hardcoded default \"changeit\" ℹ️\n\n")