V2bX/cmd/x25519.go

67 lines
1.4 KiB
Go
Raw Normal View History

2023-06-01 13:41:01 -04:00
package cmd
import (
"crypto/rand"
"encoding/base64"
"fmt"
2023-07-15 06:13:16 -04:00
"strings"
2023-07-29 07:27:15 -04:00
"github.com/InazumaV/V2bX/common/crypt"
2023-06-01 13:41:01 -04:00
"github.com/spf13/cobra"
"golang.org/x/crypto/curve25519"
)
var x25519Command = cobra.Command{
Use: "x25519",
Short: "Generate key pair for x25519 key exchange",
Run: func(cmd *cobra.Command, args []string) {
executeX25519()
},
}
func init() {
command.AddCommand(&x25519Command)
}
func executeX25519() {
2023-07-15 07:37:44 -04:00
var output string
var err error
defer func() {
fmt.Println(output)
}()
var privateKey []byte
var publicKey []byte
2023-07-15 06:13:16 -04:00
var yes, key string
2023-07-15 07:37:44 -04:00
fmt.Println("要基于节点信息生成密钥吗?(Y/n)")
2023-07-15 06:13:16 -04:00
fmt.Scan(&yes)
if strings.ToLower(yes) == "y" {
var temp string
2023-07-15 07:37:44 -04:00
fmt.Println("请输入节点id:")
2023-07-15 06:13:16 -04:00
fmt.Scan(&temp)
key = temp
2023-07-15 07:37:44 -04:00
fmt.Println("请输入节点类型:")
fmt.Scan(&temp)
key += strings.ToLower(temp)
fmt.Println("请输入Token:")
2023-07-15 06:13:16 -04:00
fmt.Scan(&temp)
key += temp
2023-07-15 07:37:44 -04:00
privateKey = crypt.GenX25519Private([]byte(key))
} else {
privateKey = make([]byte, curve25519.ScalarSize)
if _, err = rand.Read(privateKey); err != nil {
output = Err("read rand error: ", err)
return
}
2023-06-01 13:41:01 -04:00
}
if publicKey, err = curve25519.X25519(privateKey, curve25519.Basepoint); err != nil {
output = Err("gen X25519 error: ", err)
return
2023-06-01 13:41:01 -04:00
}
2023-07-15 06:13:16 -04:00
p := base64.RawURLEncoding.EncodeToString(privateKey)
output = fmt.Sprint("Private key: ",
2023-07-15 06:13:16 -04:00
p,
"\nPublic key: ",
2023-06-01 13:41:01 -04:00
base64.RawURLEncoding.EncodeToString(publicKey))
}