github.com/sagernet/sing-box@v1.9.0-rc.20/cmd/sing-box/cmd_generate.go (about) 1 package main 2 3 import ( 4 "crypto/rand" 5 "encoding/base64" 6 "encoding/hex" 7 "os" 8 "strconv" 9 10 "github.com/sagernet/sing-box/log" 11 12 "github.com/gofrs/uuid/v5" 13 "github.com/spf13/cobra" 14 ) 15 16 var commandGenerate = &cobra.Command{ 17 Use: "generate", 18 Short: "Generate things", 19 } 20 21 func init() { 22 commandGenerate.AddCommand(commandGenerateUUID) 23 commandGenerate.AddCommand(commandGenerateRandom) 24 25 mainCommand.AddCommand(commandGenerate) 26 } 27 28 var ( 29 outputBase64 bool 30 outputHex bool 31 ) 32 33 var commandGenerateRandom = &cobra.Command{ 34 Use: "rand <length>", 35 Short: "Generate random bytes", 36 Args: cobra.ExactArgs(1), 37 Run: func(cmd *cobra.Command, args []string) { 38 err := generateRandom(args) 39 if err != nil { 40 log.Fatal(err) 41 } 42 }, 43 } 44 45 func init() { 46 commandGenerateRandom.Flags().BoolVar(&outputBase64, "base64", false, "Generate base64 string") 47 commandGenerateRandom.Flags().BoolVar(&outputHex, "hex", false, "Generate hex string") 48 } 49 50 func generateRandom(args []string) error { 51 length, err := strconv.Atoi(args[0]) 52 if err != nil { 53 return err 54 } 55 56 randomBytes := make([]byte, length) 57 _, err = rand.Read(randomBytes) 58 if err != nil { 59 return err 60 } 61 62 if outputBase64 { 63 _, err = os.Stdout.WriteString(base64.StdEncoding.EncodeToString(randomBytes) + "\n") 64 } else if outputHex { 65 _, err = os.Stdout.WriteString(hex.EncodeToString(randomBytes) + "\n") 66 } else { 67 _, err = os.Stdout.Write(randomBytes) 68 } 69 70 return err 71 } 72 73 var commandGenerateUUID = &cobra.Command{ 74 Use: "uuid", 75 Short: "Generate UUID string", 76 Args: cobra.NoArgs, 77 Run: func(cmd *cobra.Command, args []string) { 78 err := generateUUID() 79 if err != nil { 80 log.Fatal(err) 81 } 82 }, 83 } 84 85 func generateUUID() error { 86 newUUID, err := uuid.NewV4() 87 if err != nil { 88 return err 89 } 90 _, err = os.Stdout.WriteString(newUUID.String() + "\n") 91 return err 92 }