github.com/sagernet/sing-box@v1.9.0-rc.20/cmd/sing-box/cmd_generate_wireguard.go (about) 1 package main 2 3 import ( 4 "encoding/base64" 5 "os" 6 7 "github.com/sagernet/sing-box/log" 8 9 "github.com/spf13/cobra" 10 "golang.zx2c4.com/wireguard/wgctrl/wgtypes" 11 ) 12 13 func init() { 14 commandGenerate.AddCommand(commandGenerateWireGuardKeyPair) 15 commandGenerate.AddCommand(commandGenerateRealityKeyPair) 16 } 17 18 var commandGenerateWireGuardKeyPair = &cobra.Command{ 19 Use: "wg-keypair", 20 Short: "Generate WireGuard key pair", 21 Args: cobra.NoArgs, 22 Run: func(cmd *cobra.Command, args []string) { 23 err := generateWireGuardKey() 24 if err != nil { 25 log.Fatal(err) 26 } 27 }, 28 } 29 30 func generateWireGuardKey() error { 31 privateKey, err := wgtypes.GeneratePrivateKey() 32 if err != nil { 33 return err 34 } 35 os.Stdout.WriteString("PrivateKey: " + privateKey.String() + "\n") 36 os.Stdout.WriteString("PublicKey: " + privateKey.PublicKey().String() + "\n") 37 return nil 38 } 39 40 var commandGenerateRealityKeyPair = &cobra.Command{ 41 Use: "reality-keypair", 42 Short: "Generate reality key pair", 43 Args: cobra.NoArgs, 44 Run: func(cmd *cobra.Command, args []string) { 45 err := generateRealityKey() 46 if err != nil { 47 log.Fatal(err) 48 } 49 }, 50 } 51 52 func generateRealityKey() error { 53 privateKey, err := wgtypes.GeneratePrivateKey() 54 if err != nil { 55 return err 56 } 57 publicKey := privateKey.PublicKey() 58 os.Stdout.WriteString("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey[:]) + "\n") 59 os.Stdout.WriteString("PublicKey: " + base64.RawURLEncoding.EncodeToString(publicKey[:]) + "\n") 60 return nil 61 }