forked from axllent/wireguard-vanity-keygen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
58 lines (48 loc) · 1.33 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
54
55
56
57
58
package main
import (
"crypto/rand"
"encoding/base64"
"golang.org/x/crypto/curve25519"
)
// KeySize defines the size of the key
const KeySize = 32
// Key is curve25519 key.
// It is used by WireGuard to represent public and preshared keys.
type Key [KeySize]byte
// PrivateKey is curve25519 key.
// It is used by WireGuard to represent private keys.
type PrivateKey [KeySize]byte
// NewPrivateKey generates a new curve25519 secret key.
// It conforms to the format described on https://cr.yp.to/ecdh.html.
func newPrivateKey() (PrivateKey, error) {
k, err := newPresharedKey()
if err != nil {
return PrivateKey{}, err
}
k[0] &= 248
k[31] = (k[31] & 127) | 64
return (PrivateKey)(*k), nil
}
// NewPresharedKey generates a new key
func newPresharedKey() (*Key, error) {
var k [KeySize]byte
_, err := rand.Read(k[:])
if err != nil {
return nil, err
}
return (*Key)(&k), nil
}
// Public computes the public key matching this curve25519 secret key.
func (k *PrivateKey) Public() Key {
var p [KeySize]byte
curve25519.ScalarBaseMult(&p, (*[KeySize]byte)(k))
return (Key)(p)
}
// String returns a private key as a string
func (k *PrivateKey) String() string {
return base64.StdEncoding.EncodeToString(k[:])
}
// String returns a public key as a string
func (k Key) String() string {
return base64.StdEncoding.EncodeToString(k[:])
}