github.com/sagernet/sing-box@v1.9.0-rc.20/cmd/sing-box/cmd_generate_tls.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"time"
     6  
     7  	"github.com/sagernet/sing-box/common/tls"
     8  	"github.com/sagernet/sing-box/log"
     9  
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  var flagGenerateTLSKeyPairMonths int
    14  
    15  var commandGenerateTLSKeyPair = &cobra.Command{
    16  	Use:   "tls-keypair <server_name>",
    17  	Short: "Generate TLS self sign key pair",
    18  	Args:  cobra.ExactArgs(1),
    19  	Run: func(cmd *cobra.Command, args []string) {
    20  		err := generateTLSKeyPair(args[0])
    21  		if err != nil {
    22  			log.Fatal(err)
    23  		}
    24  	},
    25  }
    26  
    27  func init() {
    28  	commandGenerateTLSKeyPair.Flags().IntVarP(&flagGenerateTLSKeyPairMonths, "months", "m", 1, "Valid months")
    29  	commandGenerate.AddCommand(commandGenerateTLSKeyPair)
    30  }
    31  
    32  func generateTLSKeyPair(serverName string) error {
    33  	privateKeyPem, publicKeyPem, err := tls.GenerateKeyPair(time.Now, serverName, time.Now().AddDate(0, flagGenerateTLSKeyPairMonths, 0))
    34  	if err != nil {
    35  		return err
    36  	}
    37  	os.Stdout.WriteString(string(privateKeyPem) + "\n")
    38  	os.Stdout.WriteString(string(publicKeyPem) + "\n")
    39  	return nil
    40  }