package wireguard import ( "crypto/rand" "encoding/base64" "fmt" "golang.org/x/crypto/curve25519" ) type ServerConfig struct { PrivateKey string PublicKey string Port int Interface string Address string } type ClientConfig struct { PrivateKey string PublicKey string Address string ServerIP string ServerPort int ServerPublicKey string AllowedIPs string Endpoint string } func GenerateServerConfig(port int, interfaceName, address string) (*ServerConfig, error) { privateKey, publicKey, err := generateKeyPair() if err != nil { return nil, fmt.Errorf("failed to generate key pair: %w", err) } return &ServerConfig{ PrivateKey: privateKey, PublicKey: publicKey, Port: port, Interface: interfaceName, Address: address, }, nil } func (sc *ServerConfig) ToConfigFile() string { return fmt.Sprintf(`[Interface] PrivateKey = %s Address = %s ListenPort = %d `, sc.PrivateKey, sc.Address, sc.Port) } func GenerateClientConfig(serverIP string, serverPort int, serverPublicKey, clientPrivateKey, clientPublicKey, clientAddress, allowedIPs string) *ClientConfig { return &ClientConfig{ PrivateKey: clientPrivateKey, PublicKey: clientPublicKey, Address: clientAddress, ServerIP: serverIP, ServerPort: serverPort, ServerPublicKey: serverPublicKey, AllowedIPs: allowedIPs, Endpoint: fmt.Sprintf("%s:%d", serverIP, serverPort), } } func (cc *ClientConfig) ToConfigFile() string { return fmt.Sprintf(`[Interface] PrivateKey = %s Address = %s [Peer] PublicKey = %s Endpoint = %s AllowedIPs = %s PersistentKeepalive = 25 `, cc.PrivateKey, cc.Address, cc.ServerPublicKey, cc.Endpoint, cc.AllowedIPs) } func generateKeyPair() (string, string, error) { var privateKey [32]byte if _, err := rand.Read(privateKey[:]); err != nil { return "", "", fmt.Errorf("failed to generate private key: %w", err) } privateKey[0] &= 248 privateKey[31] &= 127 privateKey[31] |= 64 var publicKey [32]byte curve25519.ScalarBaseMult(&publicKey, &privateKey) privateKeyBase64 := base64.StdEncoding.EncodeToString(privateKey[:]) publicKeyBase64 := base64.StdEncoding.EncodeToString(publicKey[:]) return privateKeyBase64, publicKeyBase64, nil } func GenerateClientKeyPair() (string, string, error) { return generateKeyPair() }