You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generate_cert.go 4.3 KiB

log: new interface New logging interface simplifies and generalizes. 1) Loggers now have only one output. 2) log.Stdout, Stderr, Crash and friends are gone. Logging is now always to standard error by default. 3) log.Panic* replaces log.Crash*. 4) Exiting and panicking are not part of the logger's state; instead the functions Exit* and Panic* simply call Exit or panic after printing. 5) There is now one 'standard logger'. Instead of calling Stderr, use Print etc. There are now triples, by analogy with fmt: Print, Println, Printf What was log.Stderr is now best represented by log.Println, since there are now separate Print and Println functions (and methods). 6) New functions SetOutput, SetFlags, and SetPrefix allow global editing of the standard logger's properties. This is new functionality. For instance, one can call log.SetFlags(log.Lshortfile|log.Ltime|log.Lmicroseconds) to get all logging output to show file name, line number, and time stamp. In short, for most purposes log.Stderr -> log.Println or log.Print log.Stderrf -> log.Printf log.Crash -> log.Panicln or log.Panic log.Crashf -> log.Panicf log.Exit -> log.Exitln or log.Exit log.Exitf -> log.Exitf (no change) This has a slight breakage: since loggers now write only to one output, existing calls to log.New() need to delete the second argument. Also, custom loggers with exit or panic properties will need to be reworked. All package code updated to new interface. The test has been reworked somewhat. The old interface will be removed after the new release. For now, its elements are marked 'deprecated' in their comments. Fixes #1184. R=rsc CC=golang-dev https://golang.org/cl/2419042
14 年之前
log: new interface New logging interface simplifies and generalizes. 1) Loggers now have only one output. 2) log.Stdout, Stderr, Crash and friends are gone. Logging is now always to standard error by default. 3) log.Panic* replaces log.Crash*. 4) Exiting and panicking are not part of the logger's state; instead the functions Exit* and Panic* simply call Exit or panic after printing. 5) There is now one 'standard logger'. Instead of calling Stderr, use Print etc. There are now triples, by analogy with fmt: Print, Println, Printf What was log.Stderr is now best represented by log.Println, since there are now separate Print and Println functions (and methods). 6) New functions SetOutput, SetFlags, and SetPrefix allow global editing of the standard logger's properties. This is new functionality. For instance, one can call log.SetFlags(log.Lshortfile|log.Ltime|log.Lmicroseconds) to get all logging output to show file name, line number, and time stamp. In short, for most purposes log.Stderr -> log.Println or log.Print log.Stderrf -> log.Printf log.Crash -> log.Panicln or log.Panic log.Crashf -> log.Panicf log.Exit -> log.Exitln or log.Exit log.Exitf -> log.Exitf (no change) This has a slight breakage: since loggers now write only to one output, existing calls to log.New() need to delete the second argument. Also, custom loggers with exit or panic properties will need to be reworked. All package code updated to new interface. The test has been reworked somewhat. The old interface will be removed after the new release. For now, its elements are marked 'deprecated' in their comments. Fixes #1184. R=rsc CC=golang-dev https://golang.org/cl/2419042
14 年之前
log: new interface New logging interface simplifies and generalizes. 1) Loggers now have only one output. 2) log.Stdout, Stderr, Crash and friends are gone. Logging is now always to standard error by default. 3) log.Panic* replaces log.Crash*. 4) Exiting and panicking are not part of the logger's state; instead the functions Exit* and Panic* simply call Exit or panic after printing. 5) There is now one 'standard logger'. Instead of calling Stderr, use Print etc. There are now triples, by analogy with fmt: Print, Println, Printf What was log.Stderr is now best represented by log.Println, since there are now separate Print and Println functions (and methods). 6) New functions SetOutput, SetFlags, and SetPrefix allow global editing of the standard logger's properties. This is new functionality. For instance, one can call log.SetFlags(log.Lshortfile|log.Ltime|log.Lmicroseconds) to get all logging output to show file name, line number, and time stamp. In short, for most purposes log.Stderr -> log.Println or log.Print log.Stderrf -> log.Printf log.Crash -> log.Panicln or log.Panic log.Crashf -> log.Panicf log.Exit -> log.Exitln or log.Exit log.Exitf -> log.Exitf (no change) This has a slight breakage: since loggers now write only to one output, existing calls to log.New() need to delete the second argument. Also, custom loggers with exit or panic properties will need to be reworked. All package code updated to new interface. The test has been reworked somewhat. The old interface will be removed after the new release. For now, its elements are marked 'deprecated' in their comments. Fixes #1184. R=rsc CC=golang-dev https://golang.org/cl/2419042
14 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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.
  4. // +build ignore
  5. // Generate a self-signed X.509 certificate for a TLS server. Outputs to
  6. // 'cert.pem' and 'key.pem' and will overwrite existing files.
  7. package main
  8. import (
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/x509"
  14. "crypto/x509/pkix"
  15. "encoding/pem"
  16. "flag"
  17. "fmt"
  18. "log"
  19. "math/big"
  20. "net"
  21. "os"
  22. "strings"
  23. "time"
  24. )
  25. var (
  26. host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for")
  27. validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011")
  28. validFor = flag.Duration("duration", 365*24*time.Hour, "Duration that certificate is valid for")
  29. isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority")
  30. rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set")
  31. ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521")
  32. )
  33. func publicKey(priv interface{}) interface{} {
  34. switch k := priv.(type) {
  35. case *rsa.PrivateKey:
  36. return &k.PublicKey
  37. case *ecdsa.PrivateKey:
  38. return &k.PublicKey
  39. default:
  40. return nil
  41. }
  42. }
  43. func pemBlockForKey(priv interface{}) *pem.Block {
  44. switch k := priv.(type) {
  45. case *rsa.PrivateKey:
  46. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
  47. case *ecdsa.PrivateKey:
  48. b, err := x509.MarshalECPrivateKey(k)
  49. if err != nil {
  50. fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err)
  51. os.Exit(2)
  52. }
  53. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  54. default:
  55. return nil
  56. }
  57. }
  58. func main() {
  59. flag.Parse()
  60. if len(*host) == 0 {
  61. log.Fatalf("Missing required --host parameter")
  62. }
  63. var priv interface{}
  64. var err error
  65. switch *ecdsaCurve {
  66. case "":
  67. priv, err = rsa.GenerateKey(rand.Reader, *rsaBits)
  68. case "P224":
  69. priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
  70. case "P256":
  71. priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  72. case "P384":
  73. priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  74. case "P521":
  75. priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  76. default:
  77. fmt.Fprintf(os.Stderr, "Unrecognized elliptic curve: %q", *ecdsaCurve)
  78. os.Exit(1)
  79. }
  80. if err != nil {
  81. log.Fatalf("failed to generate private key: %s", err)
  82. }
  83. var notBefore time.Time
  84. if len(*validFrom) == 0 {
  85. notBefore = time.Now()
  86. } else {
  87. notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom)
  88. if err != nil {
  89. fmt.Fprintf(os.Stderr, "Failed to parse creation date: %s\n", err)
  90. os.Exit(1)
  91. }
  92. }
  93. notAfter := notBefore.Add(*validFor)
  94. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  95. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  96. if err != nil {
  97. log.Fatalf("failed to generate serial number: %s", err)
  98. }
  99. template := x509.Certificate{
  100. SerialNumber: serialNumber,
  101. Subject: pkix.Name{
  102. Organization: []string{"Acme Co"},
  103. },
  104. NotBefore: notBefore,
  105. NotAfter: notAfter,
  106. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  107. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  108. BasicConstraintsValid: true,
  109. }
  110. hosts := strings.Split(*host, ",")
  111. for _, h := range hosts {
  112. if ip := net.ParseIP(h); ip != nil {
  113. template.IPAddresses = append(template.IPAddresses, ip)
  114. } else {
  115. template.DNSNames = append(template.DNSNames, h)
  116. }
  117. }
  118. if *isCA {
  119. template.IsCA = true
  120. template.KeyUsage |= x509.KeyUsageCertSign
  121. }
  122. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  123. if err != nil {
  124. log.Fatalf("Failed to create certificate: %s", err)
  125. }
  126. certOut, err := os.Create("cert.pem")
  127. if err != nil {
  128. log.Fatalf("failed to open cert.pem for writing: %s", err)
  129. }
  130. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  131. certOut.Close()
  132. log.Print("written cert.pem\n")
  133. keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  134. if err != nil {
  135. log.Print("failed to open key.pem for writing:", err)
  136. return
  137. }
  138. pem.Encode(keyOut, pemBlockForKey(priv))
  139. keyOut.Close()
  140. log.Print("written key.pem\n")
  141. }