Left: | ||
Right: |
OLD | NEW |
---|---|
(Empty) | |
1 // Generate a self-signed X.509 certificate for a TLS server. | |
adg
2010/07/01 22:08:23
Should mention that cert.pem and key.pem will be [
agl1
2010/07/01 22:11:42
Done.
| |
2 | |
3 package main | |
4 | |
5 import ( | |
6 "crypto/rsa" | |
7 "crypto/x509" | |
8 "encoding/pem" | |
9 "fmt" | |
10 "log" | |
11 "os" | |
12 "time" | |
13 ) | |
14 | |
15 func main() { | |
16 if len(os.Args) != 2 { | |
17 fmt.Printf("Usage: %s <hostname of server>\n", os.Args[0]) | |
18 return | |
19 } | |
20 | |
21 hostName := os.Args[1] | |
22 | |
23 urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0) | |
24 if err != nil { | |
25 log.Crashf("failed to open /dev/urandom: %s\n", err) | |
26 return | |
27 } | |
28 | |
29 log.Stdoutf("Generating RSA key\n") | |
30 priv, err := rsa.GenerateKey(urandom, 1024) | |
31 if err != nil { | |
32 log.Crashf("failed to generate private key: %s\n", err) | |
33 return | |
34 } | |
35 | |
36 now := time.Seconds() | |
37 | |
38 template := x509.Certificate{ | |
39 SerialNumber: []byte{0}, | |
40 Subject: x509.Name{ | |
41 CommonName: hostName, | |
42 Organization: "Acme Co", | |
43 }, | |
44 NotBefore: time.SecondsToUTC(now - 300), | |
45 NotAfter: time.SecondsToUTC(now + 86400*365), // valid for 1 ye ar. | |
46 | |
47 SubjectKeyId: []byte{1, 2, 3, 4}, | |
48 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigita lSignature, | |
49 } | |
50 | |
51 derBytes, err := x509.CreateCertificate(urandom, &template, &template, & priv.PublicKey, priv) | |
52 if err != nil { | |
53 log.Crashf("Failed to create certificate: %s", err) | |
54 return | |
55 } | |
56 | |
57 certOut, err := os.Open("cert.pem", os.O_WRONLY|os.O_CREAT, 0644) | |
58 if err != nil { | |
59 log.Crashf("failed to open cert.pem for writing: %s\n", err) | |
60 return | |
61 } | |
62 pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) | |
63 certOut.Close() | |
64 log.Stdoutf("written cert.pem\n") | |
65 | |
66 keyOut, err := os.Open("key.pem", os.O_WRONLY|os.O_CREAT, 0600) | |
67 if err != nil { | |
68 log.Crashf("failed to open key.pem for writing: %s\n", err) | |
69 return | |
70 } | |
71 pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.Marsh alPKCS1PrivateKey(priv)}) | |
72 keyOut.Close() | |
73 log.Stdoutf("written key.pem\n") | |
74 } | |
OLD | NEW |