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

     1  //go:build go1.20
     2  
     3  package main
     4  
     5  import (
     6  	"crypto/ecdh"
     7  	"crypto/rand"
     8  	"encoding/base64"
     9  	"os"
    10  
    11  	"github.com/sagernet/sing-box/log"
    12  
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  var commandGenerateVAPIDKeyPair = &cobra.Command{
    17  	Use:   "vapid-keypair",
    18  	Short: "Generate VAPID key pair",
    19  	Run: func(cmd *cobra.Command, args []string) {
    20  		err := generateVAPIDKeyPair()
    21  		if err != nil {
    22  			log.Fatal(err)
    23  		}
    24  	},
    25  }
    26  
    27  func init() {
    28  	commandGenerate.AddCommand(commandGenerateVAPIDKeyPair)
    29  }
    30  
    31  func generateVAPIDKeyPair() error {
    32  	privateKey, err := ecdh.P256().GenerateKey(rand.Reader)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	publicKey := privateKey.PublicKey()
    37  	os.Stdout.WriteString("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey.Bytes()) + "\n")
    38  	os.Stdout.WriteString("PublicKey: " + base64.RawURLEncoding.EncodeToString(publicKey.Bytes()) + "\n")
    39  	return nil
    40  }