2023-08-04 13:34:18 +02:00
|
|
|
package domain
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
)
|
|
|
|
|
|
|
|
type KeyPair struct {
|
|
|
|
PrivateKey string
|
|
|
|
PublicKey string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p KeyPair) GetPrivateKeyBytes() []byte {
|
|
|
|
data, _ := base64.StdEncoding.DecodeString(p.PrivateKey)
|
|
|
|
return data
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p KeyPair) GetPublicKeyBytes() []byte {
|
|
|
|
data, _ := base64.StdEncoding.DecodeString(p.PublicKey)
|
|
|
|
return data
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p KeyPair) GetPrivateKey() wgtypes.Key {
|
|
|
|
key, _ := wgtypes.ParseKey(p.PrivateKey)
|
|
|
|
return key
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p KeyPair) GetPublicKey() wgtypes.Key {
|
|
|
|
key, _ := wgtypes.ParseKey(p.PublicKey)
|
|
|
|
return key
|
|
|
|
}
|
|
|
|
|
|
|
|
type PreSharedKey string
|
|
|
|
|
2025-03-23 23:09:47 +01:00
|
|
|
// NewFreshKeypair generates a new key pair.
|
2023-08-04 13:34:18 +02:00
|
|
|
func NewFreshKeypair() (KeyPair, error) {
|
|
|
|
privateKey, err := wgtypes.GeneratePrivateKey()
|
|
|
|
if err != nil {
|
|
|
|
return KeyPair{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return KeyPair{
|
|
|
|
PrivateKey: privateKey.String(),
|
|
|
|
PublicKey: privateKey.PublicKey().String(),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2025-03-23 23:09:47 +01:00
|
|
|
// NewPreSharedKey generates a new pre-shared key.
|
2023-08-04 13:34:18 +02:00
|
|
|
func NewPreSharedKey() (PreSharedKey, error) {
|
|
|
|
preSharedKey, err := wgtypes.GenerateKey()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return PreSharedKey(preSharedKey.String()), nil
|
|
|
|
}
|
|
|
|
|
2025-03-23 23:09:47 +01:00
|
|
|
// PublicKeyFromPrivateKey returns the public key for a given private key.
|
|
|
|
// If the private key is invalid, an empty string is returned.
|
2023-08-04 13:34:18 +02:00
|
|
|
func PublicKeyFromPrivateKey(key string) string {
|
|
|
|
privKey, err := wgtypes.ParseKey(key)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return privKey.PublicKey().String()
|
|
|
|
}
|