فهرست منبع

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 <github@filippo.io>
Martin Tournoij 4 سال پیش
والد
کامیت
c12e24244a
1فایلهای تغییر یافته به همراه16 افزوده شده و 7 حذف شده
  1. 16 7
      cert.go

+ 16 - 7
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")