keygen.go raw
1 // Package wireguard provides an embedded WireGuard VPN server for secure
2 // NIP-46 bunker access. It uses wireguard-go with gVisor netstack for
3 // userspace networking (no root required).
4 package wireguard
5
6 import (
7 "crypto/rand"
8
9 "golang.org/x/crypto/curve25519"
10 )
11
12 // GenerateKeyPair generates a new Curve25519 keypair for WireGuard.
13 // Returns the private key and public key as 32-byte slices.
14 func GenerateKeyPair() (privateKey, publicKey []byte, err error) {
15 privateKey = make([]byte, 32)
16 if _, err = rand.Read(privateKey); err != nil {
17 return nil, nil, err
18 }
19
20 // Curve25519 clamping (required by WireGuard spec)
21 privateKey[0] &= 248
22 privateKey[31] &= 127
23 privateKey[31] |= 64
24
25 // Derive public key from private key
26 publicKey = make([]byte, 32)
27 curve25519.ScalarBaseMult((*[32]byte)(publicKey), (*[32]byte)(privateKey))
28
29 return privateKey, publicKey, nil
30 }
31
32 // DerivePublicKey derives the public key from a private key.
33 func DerivePublicKey(privateKey []byte) (publicKey []byte, err error) {
34 if len(privateKey) != 32 {
35 return nil, ErrInvalidKeyLength
36 }
37
38 publicKey = make([]byte, 32)
39 curve25519.ScalarBaseMult((*[32]byte)(publicKey), (*[32]byte)(privateKey))
40
41 return publicKey, nil
42 }
43