-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.go
95 lines (81 loc) · 2.08 KB
/
misc.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package hkontroller
import (
"crypto/md5"
"crypto/rand"
"encoding/hex"
"github.com/hkontrol/hkontroller/ed25519"
"strings"
)
func deleteFieldFromDict(val *map[string]interface{}, field string) {
for k, v := range *val {
if k == field {
delete(*val, k)
} else {
deleteFieldFromInterface(&v, field)
}
}
}
func deleteFieldFromArray(val *[]interface{}, field string) {
for _, v := range *val {
deleteFieldFromInterface(&v, field)
}
}
func deleteFieldFromInterface(val *interface{}, field string) {
v := *val
if dict, ok := v.(map[string]interface{}); ok == true {
deleteFieldFromDict(&dict, field)
}
if array, ok := v.([]interface{}); ok == true {
deleteFieldFromArray(&array, field)
}
}
// generateKeyPair generates random public and private key pair
func generateKeyPair() (KeyPair, error) {
str := randHex()
public, private, err := ed25519.GenerateKey(str)
return KeyPair{public[:], private[:]}, err
}
func GenerateKeyPair() (KeyPair, error) {
return generateKeyPair()
}
// randomHex returns a random hex string.
func randHex() string {
var b [16]byte
// Read might block
// > crypto/rand: blocked for 60 seconds waiting to read random data from the kernel
// > https://github.com/golang/go/commit/1961d8d72a53e780effa18bfa8dbe4e4282df0b2
_, err := rand.Read(b[:])
if err != nil {
panic(err)
}
var out [32]byte
for i := 0; i < len(b); i++ {
out[i*2] = btoh((b[i] >> 4) & 0xF)
out[i*2+1] = btoh(b[i] & 0xF)
}
return string(out[:])
}
func btoh(i byte) byte {
if i > 9 {
return 0x61 + (i - 10)
}
return 0x30 + i
}
// mac48Address returns a MAC-48-like address from the argument string
func mac48Address(input string) string {
h := md5.New()
h.Write([]byte(input))
result := h.Sum(nil)
var c []string
c = append(c, toHex(result[0]))
c = append(c, toHex(result[1]))
c = append(c, toHex(result[2]))
c = append(c, toHex(result[3]))
c = append(c, toHex(result[4]))
c = append(c, toHex(result[5]))
// setup id needs the mac address in upper case
return strings.ToUpper(strings.Join(c, ":"))
}
func toHex(b byte) string {
return hex.EncodeToString([]byte{b})
}