-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverside.go
85 lines (67 loc) · 1.8 KB
/
serverside.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
package capka
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"io"
"log"
"time"
"github.com/go-faster/errors"
"github.com/jamesruan/sodium"
)
var Nonces = map[string]any{}
func RandomBytes(length int) []byte {
buf := make([]byte, length)
if _, err := rand.Read(buf); err != nil {
log.Fatal(errors.Wrap(err, "generating random bytes should never fail"))
}
return buf
}
func RandomString(length int) string {
return base64.StdEncoding.EncodeToString(RandomBytes(length))
}
func GetNonce(length int, age time.Duration) string {
nonce := RandomString(length)
Nonces[nonce] = nil
go func() {
time.Sleep(age)
delete(Nonces, nonce)
}()
return nonce
}
func DecodeLoginRequestJSON(from io.Reader) (*LoginRequest, error) {
req := &LoginRequest{}
if err := json.NewDecoder(from).Decode(req); err != nil {
return nil, errors.Wrap(err, "could not decode login request JSON")
}
return req, nil
}
func (req *LoginRequest) Decode(key sodium.SignPublicKey) (*LoginData, error) {
nonce, err := base64.StdEncoding.DecodeString(req.Nonce)
if err != nil {
return nil, errors.Wrap(err, "could not decode nonce")
}
ephKey, err := base64.StdEncoding.DecodeString(req.EphKey)
if err != nil {
return nil, errors.Wrap(err, "could not decode ephkey")
}
signature, err := base64.StdEncoding.DecodeString(req.Signature)
if err != nil {
return nil, errors.Wrap(err, "could not decode signature")
}
data := &LoginData{
User: req.User,
Nonce: nonce,
EphKey: ephKey,
}
if err := data.MakeSigInput().SignVerifyDetached(
sodium.Signature{Bytes: signature},
key,
); err != nil {
return nil, errors.Wrap(err, "signature verification failed")
}
return data, nil
}
func (req *LoginData) Encrypt(data sodium.Bytes) sodium.Bytes {
return data.SealedBox(sodium.BoxPublicKey{Bytes: req.EphKey})
}