-
Notifications
You must be signed in to change notification settings - Fork 1
/
encrypter.go
89 lines (72 loc) · 1.98 KB
/
encrypter.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
package plasma
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"errors"
"sync"
)
const (
keyBitSize = 1024
verifyTokenLength = 4
)
type SessionEncrypter interface {
PublicKey() []byte
GenerateVerifyToken(r *Request) ([]byte, error)
DecryptAndVerifySharedSecret(r *Request, sharedSecret, verifyToken []byte) ([]byte, error)
}
type DefaultSessionEncrypter struct {
privateKey *rsa.PrivateKey
mu sync.Mutex
publicKey []byte
verifyTokens map[*conn][]byte
}
func NewDefaultSessionEncrypter() (SessionEncrypter, error) {
key, err := rsa.GenerateKey(rand.Reader, keyBitSize)
if err != nil {
return nil, err
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return nil, err
}
return &DefaultSessionEncrypter{
privateKey: key,
publicKey: publicKey,
mu: sync.Mutex{},
verifyTokens: map[*conn][]byte{},
}, nil
}
func (encrypter *DefaultSessionEncrypter) PublicKey() []byte {
encrypter.mu.Lock()
defer encrypter.mu.Unlock()
return encrypter.publicKey
}
func (encrypter *DefaultSessionEncrypter) GenerateVerifyToken(r *Request) ([]byte, error) {
encrypter.mu.Lock()
defer encrypter.mu.Unlock()
verifyToken := make([]byte, verifyTokenLength)
if _, err := rand.Read(verifyToken); err != nil {
return nil, err
}
encrypter.verifyTokens[r.conn] = verifyToken
return verifyToken, nil
}
func (encrypter *DefaultSessionEncrypter) DecryptAndVerifySharedSecret(r *Request, sharedSecret, verifyToken []byte) ([]byte, error) {
encrypter.mu.Lock()
defer encrypter.mu.Unlock()
token, ok := encrypter.verifyTokens[r.conn]
if !ok {
return nil, errors.New("no verify token registered")
}
delete(encrypter.verifyTokens, r.conn)
verifyToken, err := encrypter.privateKey.Decrypt(rand.Reader, verifyToken, nil)
if err != nil {
return nil, err
}
if !bytes.Equal(verifyToken, token) {
return nil, errors.New("verify token did not match")
}
return encrypter.privateKey.Decrypt(rand.Reader, sharedSecret, nil)
}