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
|
package router
import (
"encoding/base64"
"log/slog"
"sync"
"golang.org/x/crypto/argon2"
)
type ClientCache struct {
hashMap map[string][]byte
mutexMap map[string]*sync.Mutex
salt []byte
}
var CCache *ClientCache
func NewClientCache(salt []byte) *ClientCache {
return &ClientCache{
hashMap: make(map[string][]byte),
mutexMap: make(map[string]*sync.Mutex),
salt: salt,
}
}
func (c *ClientCache) GetHash(id string) []byte {
if val, ok := c.hashMap[id]; ok {
slog.Debug("gave an old hash", slog.String("hash", base64.RawStdEncoding.EncodeToString(val)))
return val
}
if _, ok := c.mutexMap[id]; !ok {
c.mutexMap[id] = &sync.Mutex{}
}
c.mutexMap[id].Lock()
defer c.mutexMap[id].Unlock()
if val, ok := c.hashMap[id]; ok {
slog.Debug("gave a newly generated hash", slog.String("hash", base64.RawStdEncoding.EncodeToString(val)))
return val
}
c.hashMap[id] = argon2.IDKey([]byte(id), c.salt, 1, 64*1024, 4, 32)
slog.Debug("generated hash", slog.String("hash", base64.RawStdEncoding.EncodeToString(c.hashMap[id])))
return c.hashMap[id]
}
|