gencert.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /*
  2. Package cryptutil contains cryptographic utility functions.
  3. Certificate generation code based on:
  4. go source src/crypto/tls/generate_cert.go
  5. Copyright 2009 The Go Authors. All rights reserved.
  6. Use of this source code is governed by a BSD-style license.
  7. */
  8. package cryptutil
  9. import (
  10. "crypto/ecdsa"
  11. "crypto/elliptic"
  12. "crypto/rand"
  13. "crypto/rsa"
  14. "crypto/x509"
  15. "crypto/x509/pkix"
  16. "encoding/pem"
  17. "errors"
  18. "fmt"
  19. "math/big"
  20. "net"
  21. "os"
  22. "strings"
  23. "time"
  24. )
  25. /*
  26. GenCert generates certificate files in a given path.
  27. path - Path to generate the certificate in.
  28. certFile - Certificate file to generate.
  29. keyFile - Key file to generate.
  30. host - Comma-separated hostnames and IPs to generate a certificate for.
  31. validFrom - Creation date formatted as Jan 1 15:04:05 2011. Default is empty string which means now.
  32. validFor - Duration that certificate is valid for. Default is 365*24*time.Hour.
  33. isCA - Flag whether this cert should be its own Certificate Authority.
  34. rsaBits - Size of RSA key to generate. Ignored if ecdsa-curve is set. Default is 2048.
  35. ecdsaCurve - ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521 or empty string (not set).
  36. */
  37. func GenCert(path string, certFile string, keyFile string, host string,
  38. validFrom string, validFor time.Duration, isCA bool, rsaBits int, ecdsaCurve string) error {
  39. var err error
  40. // Check parameters
  41. if path != "" && !strings.HasSuffix(path, "/") {
  42. path += "/"
  43. }
  44. if host == "" {
  45. return errors.New("Host required for certificate generation")
  46. }
  47. var notBefore time.Time
  48. if validFrom == "" {
  49. notBefore = time.Now()
  50. } else {
  51. notBefore, err = time.Parse("Jan 2 15:04:05 2006", validFrom)
  52. if err != nil {
  53. return fmt.Errorf("Failed to parse creation date: %s", err)
  54. }
  55. }
  56. notAfter := notBefore.Add(validFor)
  57. // Generate private key
  58. var priv interface{}
  59. switch ecdsaCurve {
  60. case "":
  61. priv, err = rsa.GenerateKey(rand.Reader, rsaBits)
  62. case "P224":
  63. priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
  64. case "P256":
  65. priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  66. case "P384":
  67. priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  68. case "P521":
  69. priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  70. default:
  71. err = fmt.Errorf("Unrecognized elliptic curve: %q", ecdsaCurve)
  72. }
  73. if err != nil {
  74. return fmt.Errorf("Failed to generate private key: %s", err)
  75. }
  76. // Generate serial random number
  77. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  78. serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
  79. // Create and populate the certificate template
  80. template := x509.Certificate{
  81. SerialNumber: serialNumber,
  82. Subject: pkix.Name{
  83. Organization: []string{"Local"},
  84. },
  85. NotBefore: notBefore,
  86. NotAfter: notAfter,
  87. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  88. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  89. BasicConstraintsValid: true,
  90. }
  91. // Add hosts
  92. hosts := strings.Split(host, ",")
  93. for _, h := range hosts {
  94. if ip := net.ParseIP(h); ip != nil {
  95. template.IPAddresses = append(template.IPAddresses, ip)
  96. } else {
  97. template.DNSNames = append(template.DNSNames, h)
  98. }
  99. }
  100. // Set the CA flag
  101. if isCA {
  102. template.IsCA = isCA
  103. template.KeyUsage |= x509.KeyUsageCertSign
  104. }
  105. // Create the certificate and write it out
  106. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
  107. if err == nil {
  108. certOut, err := os.Create(path + certFile)
  109. defer certOut.Close()
  110. if err != nil {
  111. return fmt.Errorf("Failed to open %s for writing: %s", certFile, err)
  112. }
  113. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  114. // Write out private key
  115. keyOut, err := os.OpenFile(path+keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  116. defer keyOut.Close()
  117. if err != nil {
  118. return fmt.Errorf("Failed to open %v for writing: %v", keyFile, err)
  119. }
  120. pem.Encode(keyOut, pemBlockForKey(priv))
  121. }
  122. return err
  123. }
  124. /*
  125. Return public key from a given key pair.
  126. */
  127. func publicKey(priv interface{}) interface{} {
  128. switch k := priv.(type) {
  129. case *rsa.PrivateKey:
  130. return &k.PublicKey
  131. case *ecdsa.PrivateKey:
  132. return &k.PublicKey
  133. default:
  134. return nil
  135. }
  136. }
  137. /*
  138. Return private key pem block for a given key pair.
  139. */
  140. func pemBlockForKey(priv interface{}) *pem.Block {
  141. switch k := priv.(type) {
  142. case *rsa.PrivateKey:
  143. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
  144. case *ecdsa.PrivateKey:
  145. b, _ := x509.MarshalECPrivateKey(k)
  146. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  147. default:
  148. return nil
  149. }
  150. }