XrayR/cmd/x25519.go
Senis John fd0a23bf6c
"Add option to input private key for x25519 command"
Added a command line flag to allow the user to provide an input for the private key while utilizing the x25519 command. The function `x25519` was also modified to account for the possibility of a user-inputted private key. If no private key is provided, random bytes will be generated for the private key as before. This feature provides flexibility for the user in key management.
2023-10-14 21:46:00 +08:00

63 lines
1.2 KiB
Go

package cmd
import (
"crypto/rand"
"encoding/base64"
"fmt"
"github.com/spf13/cobra"
"golang.org/x/crypto/curve25519"
)
var (
priKey string
x25519Cmd = &cobra.Command{
Use: "x25519",
Short: "Generate key pair for x25519 key exchange",
Run: func(cmd *cobra.Command, args []string) {
if err := x25519(); err != nil {
fmt.Println(err)
}
},
}
)
func init() {
x25519Cmd.PersistentFlags().StringVarP(&priKey, "input", "i", "", "Input private key (base64.RawURLEncoding)")
rootCmd.AddCommand(x25519Cmd)
}
func x25519() error {
privateKey := make([]byte, curve25519.ScalarSize)
if priKey == "" {
if _, err := rand.Read(privateKey); err != nil {
return err
}
} else {
p, err := base64.RawURLEncoding.DecodeString(priKey)
if err != nil {
return err
}
privateKey = p
}
// Modify random bytes using algorithm described at:
// https://cr.yp.to/ecdh.html.
privateKey[0] &= 248
privateKey[31] &= 127
privateKey[31] |= 64
publicKey, err := curve25519.X25519(privateKey, curve25519.Basepoint)
if err != nil {
return err
}
output := fmt.Sprintf("Private key: %v\nPublic key: %v",
base64.RawURLEncoding.EncodeToString(privateKey),
base64.RawURLEncoding.EncodeToString(publicKey))
fmt.Println(output)
return nil
}