-
Notifications
You must be signed in to change notification settings - Fork 0
/
v3.go
76 lines (68 loc) · 1.67 KB
/
v3.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package onionkey
import (
"crypto/rand"
"encoding/base32"
"encoding/base64"
"errors"
"io/ioutil"
"os"
"strings"
"github.com/wybiral/torgo"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/sha3"
)
type v3Key ed25519.PrivateKey
func generateV3() (v3Key, error) {
_, key, err := ed25519.GenerateKey(rand.Reader)
return v3Key(key), err
}
func readV3(path string) (v3Key, error) {
raw, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
pk := strings.TrimSpace(string(raw))
parts := strings.SplitN(pk, ":", 2)
if parts[0] != "v3" {
return nil, errors.New("Invalid key type")
}
seed, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return nil, err
}
key := ed25519.NewKeyFromSeed(seed)
return v3Key(key), nil
}
func (k v3Key) Onion() (*torgo.Onion, error) {
return torgo.OnionFromEd25519(ed25519.PrivateKey(k))
}
func (k v3Key) WriteFile(path string) error {
seed := ed25519.PrivateKey(k).Seed()
b64 := base64.StdEncoding.EncodeToString(seed)
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString("v3:" + b64)
if err != nil {
return err
}
return nil
}
func (k v3Key) ServiceID() string {
// Get ed25519 public key
pub := ed25519.PrivateKey(k).Public().(ed25519.PublicKey)
// Calculate check digits
checkstr := []byte(".onion checksum")
checkstr = append(checkstr, pub...)
checkstr = append(checkstr, 0x03)
checksum := sha3.Sum256(checkstr)
checkdigits := checksum[:2]
// Calculate service ID
combined := pub[:]
combined = append(combined, checkdigits...)
combined = append(combined, 0x03)
serviceID := base32.StdEncoding.EncodeToString(combined)
return strings.ToLower(serviceID)
}