-
Notifications
You must be signed in to change notification settings - Fork 33
/
client.go
81 lines (75 loc) · 1.71 KB
/
client.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
77
78
79
80
81
package client
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"github.com/golang/protobuf/proto"
"io/ioutil"
"log"
"net"
"strings"
)
func DetectHost(address string) string {
addr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
log.Fatal(err)
}
conn, err := net.ListenMulticastUDP("udp", nil, addr)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
_, udpAddr, err := conn.ReadFromUDP([]byte{0})
if err != nil {
log.Fatal(err)
}
return udpAddr.IP.String()
}
func SetHost(address string, host string) string {
parts := strings.Split(address, ":")
return host + ":" + parts[1]
}
func LoadPrivateKey(privateKeyLocation string) *rsa.PrivateKey {
if privateKeyLocation != "" {
privateKey := ReadPrivateKey(privateKeyLocation)
if privateKey != nil {
log.Print("Found private key")
return privateKey
} else {
log.Print("No private key available")
}
}
return nil
}
func ReadPrivateKey(privateKeyLocation string) *rsa.PrivateKey {
b, err := ioutil.ReadFile(privateKeyLocation)
if err != nil {
log.Fatal("Could not find private key at ", privateKeyLocation)
}
p, _ := pem.Decode(b)
if p.Type != "RSA PRIVATE KEY" {
log.Fatal("Private key type is wrong: ", p.Type)
}
privateKey, err := x509.ParsePKCS1PrivateKey(p.Bytes)
if err != nil {
log.Fatal(err)
}
return privateKey
}
func Sign(privateKey *rsa.PrivateKey, message proto.Message) []byte {
messageBytes, err := proto.Marshal(message)
if err != nil {
log.Fatal(err)
}
hash := sha256.New()
hash.Write(messageBytes)
d := hash.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, d)
if err != nil {
log.Fatal(err)
}
return signature
}