-
Notifications
You must be signed in to change notification settings - Fork 13
/
keystore.go
191 lines (157 loc) · 4.09 KB
/
keystore.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package mixin
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/binary"
"errors"
"io"
"sync"
"time"
"github.com/golang-jwt/jwt"
"golang.org/x/crypto/curve25519"
)
type Keystore struct {
ClientID string `json:"client_id"`
SessionID string `json:"session_id"`
PrivateKey string `json:"private_key"`
PinToken string `json:"pin_token"`
Scope string `json:"scope"`
// seq is increasing number
iter uint64
mux sync.Mutex
}
type KeystoreAuth struct {
*Keystore
signMethod jwt.SigningMethod
signKey interface{}
pinCipher cipher.Block
}
func AuthFromKeystore(store *Keystore) (*KeystoreAuth, error) {
auth := &KeystoreAuth{
Keystore: store,
}
signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(store.PrivateKey))
if err != nil {
return nil, err
}
auth.signKey = signKey
auth.signMethod = jwt.SigningMethodRS512
if store.PinToken != "" {
token, err := base64.StdEncoding.DecodeString(store.PinToken)
if err != nil {
return nil, err
}
keyBytes, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, signKey, token, []byte(store.SessionID))
if err != nil {
return nil, err
}
pinCipher, err := aes.NewCipher(keyBytes)
if err != nil {
return nil, err
}
auth.pinCipher = pinCipher
}
return auth, nil
}
// AuthEd25519FromKeystore produces a signer using a ed25519 keystore.
func AuthEd25519FromKeystore(store *Keystore) (*KeystoreAuth, error) {
auth := &KeystoreAuth{
Keystore: store,
signMethod: Ed25519SigningMethod,
}
signKey, err := ed25519Encoding.DecodeString(store.PrivateKey)
if err != nil {
return nil, err
}
if len(signKey) != ed25519.PrivateKeySize {
return nil, errors.New("invalid ed25519 private key")
}
auth.signKey = ed25519.PrivateKey(signKey)
if store.PinToken != "" {
token, err := ed25519Encoding.DecodeString(store.PinToken)
if err != nil {
return nil, err
}
var keyBytes, curve, pub [32]byte
privateKeyToCurve25519(&curve, signKey)
copy(pub[:], token[:])
curve25519.ScalarMult(&keyBytes, &curve, &pub)
pinCipher, err := aes.NewCipher(keyBytes[:])
if err != nil {
return nil, err
}
auth.pinCipher = pinCipher
}
return auth, nil
}
func privateKeyToCurve25519(curve25519Private *[32]byte, privateKey ed25519.PrivateKey) {
h := sha512.New()
h.Write(privateKey.Seed())
digest := h.Sum(nil)
digest[0] &= 248
digest[31] &= 127
digest[31] |= 64
copy(curve25519Private[:], digest)
}
func (k *KeystoreAuth) SignToken(signature, requestID string, exp time.Duration) string {
jwtMap := jwt.MapClaims{
"uid": k.ClientID,
"sid": k.SessionID,
"iat": time.Now().Unix(),
"exp": time.Now().Add(exp).Unix(),
"jti": requestID,
"sig": signature,
"scp": ScopeFull,
}
if k.Scope != "" {
jwtMap["scp"] = k.Scope
}
token, err := jwt.NewWithClaims(k.signMethod, jwtMap).SignedString(k.signKey)
if err != nil {
panic(err)
}
return token
}
func (k *KeystoreAuth) sequence() uint64 {
k.mux.Lock()
defer k.mux.Unlock()
if iter := uint64(time.Now().UnixNano()); iter > k.iter {
k.iter = iter
} else {
k.iter += 1
}
return k.iter
}
func (k *KeystoreAuth) EncryptPin(pin string) string {
if k.pinCipher == nil {
panic(errors.New("keystore: pin_token required"))
}
if err := ValidatePinPattern(pin); err != nil {
panic(err)
}
pinByte := []byte(pin)
timeBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(timeBytes, uint64(time.Now().Unix()))
pinByte = append(pinByte, timeBytes...)
iteratorBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(iteratorBytes, k.sequence())
pinByte = append(pinByte, iteratorBytes...)
padding := aes.BlockSize - len(pinByte)%aes.BlockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
pinByte = append(pinByte, padText...)
cipherText := make([]byte, aes.BlockSize+len(pinByte))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
mode := cipher.NewCBCEncrypter(k.pinCipher, iv)
mode.CryptBlocks(cipherText[aes.BlockSize:], pinByte)
return base64.StdEncoding.EncodeToString(cipherText)
}