|
|
|
@ -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 |
|
|
|
|
} |
|
|
|
|