~bigbes/shroud

shroud/internal/awgserver/keygen.go -rw-r--r-- 1.4 KiB
32187908 — Eugene Blikh refactor: rename Go module to go.bigb.es/shroud a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package awgserver

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"fmt"

	"golang.org/x/crypto/curve25519"
)

// GeneratePrivateKey generates a new Curve25519 private key with WireGuard clamping.
func GeneratePrivateKey() (string, error) {
	var key [32]byte
	if _, err := rand.Read(key[:]); err != nil {
		return "", fmt.Errorf("generating random key: %w", err)
	}
	// WireGuard clamping.
	key[0] &= 248
	key[31] = (key[31] & 127) | 64
	return base64.StdEncoding.EncodeToString(key[:]), nil
}

// PublicKeyFromPrivate derives the Curve25519 public key from a base64-encoded private key.
func PublicKeyFromPrivate(privBase64 string) (string, error) {
	privBytes, err := base64.StdEncoding.DecodeString(privBase64)
	if err != nil {
		return "", fmt.Errorf("decoding private key: %w", err)
	}
	if len(privBytes) != 32 {
		return "", fmt.Errorf("private key must be 32 bytes, got %d", len(privBytes))
	}
	pub, err := curve25519.X25519(privBytes, curve25519.Basepoint)
	if err != nil {
		return "", fmt.Errorf("computing public key: %w", err)
	}
	return base64.StdEncoding.EncodeToString(pub), nil
}

// base64ToHex converts a base64-encoded key to hex (UAPI format).
func base64ToHex(b64 string) (string, error) {
	raw, err := base64.StdEncoding.DecodeString(b64)
	if err != nil {
		return "", fmt.Errorf("decode base64 key: %w", err)
	}
	if len(raw) != 32 {
		return "", fmt.Errorf("key must be 32 bytes, got %d", len(raw))
	}
	return hex.EncodeToString(raw), nil
}