genkey.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Package genkey implements the genkey command.
  2. package genkey
  3. import (
  4. "encoding/json"
  5. "errors"
  6. "github.com/cloudflare/cfssl/cli"
  7. "github.com/cloudflare/cfssl/csr"
  8. "github.com/cloudflare/cfssl/initca"
  9. )
  10. var genkeyUsageText = `cfssl genkey -- generate a new key and CSR
  11. Usage of genkey:
  12. cfssl genkey CSRJSON
  13. Arguments:
  14. CSRJSON: JSON file containing the request, use '-' for reading JSON from stdin
  15. Flags:
  16. `
  17. var genkeyFlags = []string{"initca", "config"}
  18. func genkeyMain(args []string, c cli.Config) (err error) {
  19. csrFile, args, err := cli.PopFirstArgument(args)
  20. if err != nil {
  21. return
  22. }
  23. if len(args) > 0 {
  24. return errors.New("only one argument is accepted, please check with usage")
  25. }
  26. csrFileBytes, err := cli.ReadStdin(csrFile)
  27. if err != nil {
  28. return
  29. }
  30. req := csr.CertificateRequest{
  31. KeyRequest: csr.NewKeyRequest(),
  32. }
  33. err = json.Unmarshal(csrFileBytes, &req)
  34. if err != nil {
  35. return
  36. }
  37. if c.IsCA {
  38. var key, csrPEM, cert []byte
  39. cert, csrPEM, key, err = initca.New(&req)
  40. if err != nil {
  41. return
  42. }
  43. cli.PrintCert(key, csrPEM, cert)
  44. } else {
  45. if req.CA != nil {
  46. err = errors.New("ca section only permitted in initca")
  47. return
  48. }
  49. var key, csrPEM []byte
  50. g := &csr.Generator{Validator: Validator}
  51. csrPEM, key, err = g.ProcessRequest(&req)
  52. if err != nil {
  53. key = nil
  54. return
  55. }
  56. cli.PrintCert(key, csrPEM, nil)
  57. }
  58. return nil
  59. }
  60. // Validator does nothing and will never return an error. It exists because creating a
  61. // csr.Generator requires a Validator.
  62. func Validator(req *csr.CertificateRequest) error {
  63. return nil
  64. }
  65. // Command assembles the definition of Command 'genkey'
  66. var Command = &cli.Command{UsageText: genkeyUsageText, Flags: genkeyFlags, Main: genkeyMain}