-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
53 lines (37 loc) · 1.13 KB
/
crypto.go
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
51
52
53
package topology // import "github.com/nathanaelle/wireguard-topology"
import (
"crypto/rand"
"encoding/base64"
"golang.org/x/crypto/curve25519"
)
// WGKeyLen is the length of a Curve25519 key
const WGKeyLen int = 32
func genKey() ([WGKeyLen]byte, error) {
var secret [WGKeyLen]byte
_, err := rand.Read(secret[:])
// clamping : see github.com/wireguard/wireguard-tools/src/genkey.c
secret[0] &= 248
secret[31] = (secret[31] & 127) | 64
return secret, err
}
// GenPSK generate en base64 encoded PreSharedKey
func GenPSK() (psk string, err error) {
var key [WGKeyLen]byte
if key, err = genKey(); err != nil {
return
}
psk = base64.RawStdEncoding.WithPadding('=').EncodeToString(key[:])
return
}
// GenKeyPair generates a pair of base64 encoded Curve25519 keys
func GenKeyPair() (priv string, pub string, err error) {
var secret [WGKeyLen]byte
var public [WGKeyLen]byte
if secret, err = genKey(); err != nil {
return
}
curve25519.ScalarBaseMult(&public, &secret)
priv = base64.RawStdEncoding.WithPadding('=').EncodeToString(secret[:])
pub = base64.RawStdEncoding.WithPadding('=').EncodeToString(public[:])
return
}