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>
This commit is contained in:
Martin Tournoij 2020-10-27 19:34:17 +08:00 committed by GitHub
parent 6649e9d2e7
commit c12e24244a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

23
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")