gencsr.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Package gencsr implements the gencsr command.
  2. package gencsr
  3. import (
  4. "encoding/json"
  5. "errors"
  6. "github.com/cloudflare/cfssl/cli"
  7. "github.com/cloudflare/cfssl/csr"
  8. "github.com/cloudflare/cfssl/helpers"
  9. "github.com/cloudflare/cfssl/signer"
  10. )
  11. var gencsrUsageText = `cfssl gencsr -- generate a csr from a private key with existing CSR json specification or certificate
  12. Usage of gencsr:
  13. cfssl gencsr -key private_key_file [-host hostname_override] CSRJSON
  14. cfssl gencsr -key private_key_file [-host hostname_override] -cert certificate_file
  15. Arguments:
  16. CSRJSON: JSON file containing the request, use '-' for reading JSON from stdin
  17. Flags:
  18. `
  19. var gencsrFlags = []string{"key", "cert"}
  20. func gencsrMain(args []string, c cli.Config) (err error) {
  21. if c.KeyFile == "" {
  22. return errors.New("private key file is required through '-key', please check with usage")
  23. }
  24. keyBytes, err := helpers.ReadBytes(c.KeyFile)
  25. if err != nil {
  26. return err
  27. }
  28. key, err := helpers.ParsePrivateKeyPEM(keyBytes)
  29. if err != nil {
  30. return err
  31. }
  32. // prepare a stub CertificateRequest
  33. req := &csr.CertificateRequest{
  34. KeyRequest: csr.NewKeyRequest(),
  35. }
  36. if c.CertFile != "" {
  37. if len(args) > 0 {
  38. return errors.New("no argument is accepted with '-cert', please check with usage")
  39. }
  40. certBytes, err := helpers.ReadBytes(c.CertFile)
  41. if err != nil {
  42. return err
  43. }
  44. cert, err := helpers.ParseCertificatePEM(certBytes)
  45. if err != nil {
  46. return err
  47. }
  48. req = csr.ExtractCertificateRequest(cert)
  49. } else {
  50. csrFile, args, err := cli.PopFirstArgument(args)
  51. if err != nil {
  52. return err
  53. }
  54. if len(args) > 0 {
  55. return errors.New("only one argument is accepted, please check with usage")
  56. }
  57. csrFileBytes, err := cli.ReadStdin(csrFile)
  58. if err != nil {
  59. return err
  60. }
  61. err = json.Unmarshal(csrFileBytes, req)
  62. if err != nil {
  63. return err
  64. }
  65. }
  66. if c.Hostname != "" {
  67. req.Hosts = signer.SplitHosts(c.Hostname)
  68. }
  69. csrBytes, err := csr.Generate(key, req)
  70. if err != nil {
  71. return err
  72. }
  73. cli.PrintCert(keyBytes, csrBytes, nil)
  74. return nil
  75. }
  76. // Command assembles the definition of Command 'gencsr'
  77. var Command = &cli.Command{UsageText: gencsrUsageText, Flags: gencsrFlags, Main: gencsrMain}