1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Generate a self-signed X.509 certificate for a TLS server. Outputs to
8 // 'cert.pem' and 'key.pem' and will overwrite existing files.
29 host
= flag
.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for")
30 validFrom
= flag
.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011")
31 validFor
= flag
.Duration("duration", 365*24*time
.Hour
, "Duration that certificate is valid for")
32 isCA
= flag
.Bool("ca", false, "whether this cert should be its own Certificate Authority")
33 rsaBits
= flag
.Int("rsa-bits", 2048, "Size of RSA key to generate")
40 log
.Fatalf("Missing required --host parameter")
43 priv
, err
:= rsa
.GenerateKey(rand
.Reader
, *rsaBits
)
45 log
.Fatalf("failed to generate private key: %s", err
)
49 var notBefore time
.Time
50 if len(*validFrom
) == 0 {
51 notBefore
= time
.Now()
53 notBefore
, err
= time
.Parse("Jan 2 15:04:05 2006", *validFrom
)
55 fmt
.Fprintf(os
.Stderr
, "Failed to parse creation date: %s\n", err
)
60 notAfter
:= notBefore
.Add(*validFor
)
63 endOfTime
:= time
.Date(2049, 12, 31, 23, 59, 59, 0, time
.UTC
)
64 if notAfter
.After(endOfTime
) {
68 template
:= x509
.Certificate
{
69 SerialNumber
: new(big
.Int
).SetInt64(0),
71 Organization
: []string{"Acme Co"},
76 KeyUsage
: x509
.KeyUsageKeyEncipherment | x509
.KeyUsageDigitalSignature
,
77 ExtKeyUsage
: []x509
.ExtKeyUsage
{x509
.ExtKeyUsageServerAuth
},
78 BasicConstraintsValid
: true,
81 hosts
:= strings
.Split(*host
, ",")
82 for _
, h
:= range hosts
{
83 if ip
:= net
.ParseIP(h
); ip
!= nil {
84 template
.IPAddresses
= append(template
.IPAddresses
, ip
)
86 template
.DNSNames
= append(template
.DNSNames
, h
)
92 template
.KeyUsage |
= x509
.KeyUsageCertSign
95 derBytes
, err
:= x509
.CreateCertificate(rand
.Reader
, &template
, &template
, &priv
.PublicKey
, priv
)
97 log
.Fatalf("Failed to create certificate: %s", err
)
101 certOut
, err
:= os
.Create("cert.pem")
103 log
.Fatalf("failed to open cert.pem for writing: %s", err
)
106 pem
.Encode(certOut
, &pem
.Block
{Type
: "CERTIFICATE", Bytes
: derBytes
})
108 log
.Print("written cert.pem\n")
110 keyOut
, err
:= os
.OpenFile("key.pem", os
.O_WRONLY|os
.O_CREATE|os
.O_TRUNC
, 0600)
112 log
.Print("failed to open key.pem for writing:", err
)
115 pem
.Encode(keyOut
, &pem
.Block
{Type
: "RSA PRIVATE KEY", Bytes
: x509
.MarshalPKCS1PrivateKey(priv
)})
117 log
.Print("written key.pem\n")