github.com/tommi2day/pwcli@v0.0.0-20240317203041-4d1177a5ab91/cmd/genkey.go (about)

     1  // Package cmd Commands
     2  package cmd
     3  
     4  import (
     5  	"fmt"
     6  
     7  	"github.com/tommi2day/gomodules/pwlib"
     8  
     9  	log "github.com/sirupsen/logrus"
    10  
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  // generateCmd represents the generate command
    15  var generateCmd = &cobra.Command{
    16  	Use:     "genkey",
    17  	Aliases: []string{"genrsa"},
    18  	Short:   "Generate a new RSA Keypair",
    19  	Long: `Generates a new pair of rsa keys
    20  optionally you may assign an idividal key password using -p flag
    21  `,
    22  	RunE:         genkey,
    23  	SilenceUsage: true,
    24  }
    25  
    26  func genkey(cmd *cobra.Command, _ []string) error {
    27  	if method == "" {
    28  		method = typeOpenSSL
    29  	}
    30  	log.Debugf("genkey for method %s", method)
    31  	kp, _ := cmd.Flags().GetString("keypass")
    32  	if kp != "" {
    33  		pc.KeyPass = kp
    34  		log.Debugf("use alternate key password '%s'", kp)
    35  	}
    36  	switch method {
    37  	case typeGO, typeOpenSSL:
    38  		_, _, err := pwlib.GenRsaKey(pc.PubKeyFile, pc.PrivateKeyFile, pc.KeyPass)
    39  		if err == nil {
    40  			log.Infof("New key pair generated as %s and %s", pc.PubKeyFile, pc.PrivateKeyFile)
    41  			fmt.Println("DONE")
    42  		}
    43  		return err
    44  	}
    45  	return fmt.Errorf("method %s doesnt support keygeneration", method)
    46  }
    47  
    48  func init() {
    49  	RootCmd.AddCommand(generateCmd)
    50  	// don't have variables populated here
    51  	generateCmd.Flags().StringP("keypass", "p", "", "dedicated password for the private key")
    52  }