-
Notifications
You must be signed in to change notification settings - Fork 23
/
util.go
143 lines (123 loc) · 2.38 KB
/
util.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"github.com/jxskiss/base62"
"log"
"strings"
"sync"
)
func Check(e error) {
if e != nil {
log.Fatal(e)
}
}
func Ignore(e error) {}
func Unwrap[T any](value T, e error) T {
if e != nil {
log.Fatal(e)
}
return value
}
func Ptr[T any](value T) *T {
return &value
}
func PtrSlice[T any](in []T) []*T {
out := make([]*T, len(in))
i := 0
for i < len(in) {
out[i] = &in[i]
i += 1
}
return out
}
func Contains[T comparable](slice []T, target T) bool {
for _, el := range slice {
if el == target {
return true
}
}
return false
}
func ContainsPublicKey(slice []rsa.PublicKey, target *rsa.PublicKey) bool {
for _, el := range slice {
if el.Equal(target) {
return true
}
}
return false
}
func PtrEquals[T comparable](a *T, b *T) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func Truncate(data []byte, length int) []byte {
if len(data) < length {
newData := make([]byte, length)
copy(newData, data)
return newData
}
return data[:16]
}
func RandomHex(n uint) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func RandomBase62(n uint) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return base62.EncodeToString(bytes), nil
}
// Wrap string s to lines of at most n bytes
func Wrap(s string, n int) string {
var builder strings.Builder
for {
end := n
if end > len(s) {
end = len(s)
}
builder.WriteString(s[:end])
s = s[end:]
if len(s) > 0 {
builder.WriteString("\n")
} else {
break
}
}
return builder.String()
}
func SignSHA256(app *App, plaintext []byte) ([]byte, error) {
hash := sha256.New()
hash.Write(plaintext)
sum := hash.Sum(nil)
return rsa.SignPKCS1v15(rand.Reader, app.Key, crypto.SHA256, sum)
}
func SignSHA1(app *App, plaintext []byte) ([]byte, error) {
hash := sha1.New()
hash.Write(plaintext)
sum := hash.Sum(nil)
return rsa.SignPKCS1v15(rand.Reader, app.Key, crypto.SHA1, sum)
}
type KeyedMutex struct {
mutexes sync.Map
}
func (m *KeyedMutex) Lock(key string) func() {
value, _ := m.mutexes.LoadOrStore(key, &sync.Mutex{})
mtx := value.(*sync.Mutex)
mtx.Lock()
return func() { mtx.Unlock() }
}