wireguard: introduce NewKeyPair, NewPrivateKey, and PrivateKey.Public()

Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
2023-08-23 00:18:31 +00:00
parent 1d8c818ec4
commit e2f831fd6a
3 changed files with 49 additions and 0 deletions
+46
View File
@@ -2,8 +2,11 @@ package wireguard
import (
"bytes"
"crypto/rand"
"encoding/base64"
"errors"
"golang.org/x/crypto/curve25519"
)
const (
@@ -89,8 +92,51 @@ func decodeKey(data string, size int) ([]byte, error) {
}
}
// NewPrivateKey creates a new PrivateKey
func NewPrivateKey() (PrivateKey, error) {
var s [PrivateKeySize]byte
_, err := rand.Read(s[:])
if err != nil {
return []byte{}, err
}
// apply same clamping as wireguard-go/device/noise-helpers.go
s[0] &= 0xf8
s[31] = (s[31] & 0x7f) | 0x40
return s[:], nil
}
// Public generates the corresponding PublicKey
func (key PrivateKey) Public() PublicKey {
if len(key) != PrivateKeySize {
return []byte{}
}
out := [PublicKeySize]byte{}
in := (*[PrivateKeySize]byte)(key)
curve25519.ScalarBaseMult(&out, in)
return out[:]
}
// KeyPair holds a Key pair
type KeyPair struct {
PrivateKey PrivateKey
PublicKey PublicKey
}
// NewKeyPair creates a new KeyPair for Wireguard
func NewKeyPair() (*KeyPair, error) {
key, err := NewPrivateKey()
if err != nil {
return nil, err
}
out := &KeyPair{
PrivateKey: key,
PublicKey: key.Public(),
}
return out, nil
}