-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwk.go
396 lines (359 loc) · 11.1 KB
/
jwk.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Copyright 2015 realglobe, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// JWK 関係。
package jwk
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"encoding/base64"
"math/big"
"github.com/realglobe-Inc/go-lib/erro"
)
type Key interface {
// kty
Type() string
// use
Use() string
// key_ops
Operations() map[string]bool
// alg
Algorithm() string
// kid
Id() string
Public() crypto.PublicKey
Private() crypto.PrivateKey
Common() []byte
// json.Marshal すると JWK になるようなマップを返す。
ToMap() map[string]interface{}
}
type keyImpl struct {
kty string
use string
ops map[string]bool
alg string
id string
pub crypto.PublicKey
pri crypto.PrivateKey
com []byte
}
func New(rawKey interface{}, m map[string]interface{}) Key {
key := baseFromMap(m)
switch k := rawKey.(type) {
case *ecdsa.PrivateKey:
key.kty = tagEc
key.pri = k
key.pub = &k.PublicKey
case *ecdsa.PublicKey:
key.kty = tagEc
key.pub = k
case *rsa.PrivateKey:
key.kty = tagRsa
key.pri = k
key.pub = &k.PublicKey
case *rsa.PublicKey:
key.kty = tagRsa
key.pub = k
case []byte:
key.kty = tagOct
key.com = k
default:
}
return key
}
// JWK を json.Unmarshal した結果からつくる。
func FromMap(m map[string]interface{}) (k Key, err error) {
key := baseFromMap(m)
switch key.kty {
case tagEc:
key.pri, key.pub, err = ecFromMap(m)
if err != nil {
return nil, erro.Wrap(err)
}
case tagRsa:
key.pri, key.pub, err = rsaFromMap(m)
if err != nil {
return nil, erro.Wrap(err)
}
case tagOct:
key.com, err = commonFromMap(m)
if err != nil {
return nil, erro.Wrap(err)
}
default:
return nil, erro.New("unsupported key type " + key.kty)
}
return key, nil
}
func baseFromMap(m map[string]interface{}) *keyImpl {
var ops map[string]bool
if opArray, _ := m[tagKey_ops].([]interface{}); len(opArray) > 0 {
for _, opRaw := range opArray {
if op, _ := opRaw.(string); op != "" {
if ops == nil {
ops = map[string]bool{}
}
ops[op] = true
}
}
}
key := &keyImpl{ops: ops}
key.kty, _ = m[tagKty].(string)
key.use, _ = m[tagUse].(string)
key.alg, _ = m[tagAlg].(string)
key.id, _ = m[tagKid].(string)
return key
}
func ecFromMap(m map[string]interface{}) (crypto.PrivateKey, crypto.PublicKey, error) {
pub, err := ecPublicFromMap(m)
if err != nil {
return nil, nil, erro.Wrap(err)
}
var pri ecdsa.PrivateKey
if dStr, _ := m["d"].(string); dStr == "" {
// 公開鍵だった。
return nil, pub, nil
} else if dRaw, err := base64.RawURLEncoding.DecodeString(dStr); err != nil {
return nil, nil, erro.Wrap(err)
} else {
pri.PublicKey = *pub
pri.D = (&big.Int{}).SetBytes(dRaw)
}
return &pri, &pri.PublicKey, nil
}
func ecPublicFromMap(m map[string]interface{}) (*ecdsa.PublicKey, error) {
var pub ecdsa.PublicKey
switch crv, _ := m[tagCrv].(string); crv {
case "":
return nil, erro.New("no elliptic curve")
case tagP_256:
pub.Curve = elliptic.P256()
case tagP_384:
pub.Curve = elliptic.P384()
case tagP_521:
pub.Curve = elliptic.P521()
default:
return nil, erro.New("unsupoorted elliptic curve " + crv)
}
if xStr, _ := m["x"].(string); xStr == "" {
return nil, erro.New("no x")
} else if xRaw, err := base64.RawURLEncoding.DecodeString(xStr); err != nil {
return nil, erro.Wrap(err)
} else if yStr, _ := m["y"].(string); yStr == "" {
return nil, erro.New("no y")
} else if yRaw, err := base64.RawURLEncoding.DecodeString(yStr); err != nil {
return nil, erro.Wrap(err)
} else {
pub.X = (&big.Int{}).SetBytes(xRaw)
pub.Y = (&big.Int{}).SetBytes(yRaw)
}
return &pub, nil
}
func rsaFromMap(m map[string]interface{}) (crypto.PrivateKey, crypto.PublicKey, error) {
pub, err := rsaPublicFromMap(m)
if err != nil {
return nil, nil, erro.Wrap(err)
}
var pri rsa.PrivateKey
if dStr, _ := m["d"].(string); dStr == "" {
// 公開鍵だった。
return nil, pub, nil
} else if dRaw, err := base64.RawURLEncoding.DecodeString(dStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if pStr, _ := m["p"].(string); pStr == "" {
return nil, nil, erro.New("no p")
} else if pRaw, err := base64.RawURLEncoding.DecodeString(pStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if qStr, _ := m["q"].(string); qStr == "" {
return nil, nil, erro.New("no q")
} else if qRaw, err := base64.RawURLEncoding.DecodeString(qStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if dpStr, _ := m["dp"].(string); dpStr == "" {
return nil, nil, erro.New("no dp")
} else if dpRaw, err := base64.RawURLEncoding.DecodeString(dpStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if dqStr, _ := m["dq"].(string); dqStr == "" {
return nil, nil, erro.New("no dq")
} else if dqRaw, err := base64.RawURLEncoding.DecodeString(dqStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if qiStr, _ := m["qi"].(string); qiStr == "" {
return nil, nil, erro.New("no qi")
} else if qiRaw, err := base64.RawURLEncoding.DecodeString(qiStr); err != nil {
return nil, nil, erro.Wrap(err)
} else {
pri.PublicKey = *pub
pri.D = (&big.Int{}).SetBytes(dRaw)
pri.Primes = []*big.Int{(&big.Int{}).SetBytes(pRaw), (&big.Int{}).SetBytes(qRaw)}
pri.Precomputed.Dp = (&big.Int{}).SetBytes(dpRaw)
pri.Precomputed.Dq = (&big.Int{}).SetBytes(dqRaw)
pri.Precomputed.Qinv = (&big.Int{}).SetBytes(qiRaw)
pri.Precomputed.CRTValues = []rsa.CRTValue{}
}
if crts, _ := m[tagOth].([]map[string]interface{}); crts != nil {
for _, crt := range crts {
if rStr, _ := crt["r"].(string); rStr == "" {
return nil, nil, erro.New("no r")
} else if rRaw, err := base64.RawURLEncoding.DecodeString(rStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if dStr, _ := m["d"].(string); dStr == "" {
return nil, nil, erro.New("no d")
} else if dRaw, err := base64.RawURLEncoding.DecodeString(dStr); err != nil {
return nil, nil, erro.Wrap(err)
} else if tStr, _ := m["t"].(string); tStr == "" {
return nil, nil, erro.New("no t")
} else if tRaw, err := base64.RawURLEncoding.DecodeString(tStr); err != nil {
return nil, nil, erro.Wrap(err)
} else {
pri.Precomputed.CRTValues = append(pri.Precomputed.CRTValues, rsa.CRTValue{
R: (&big.Int{}).SetBytes(rRaw),
Exp: (&big.Int{}).SetBytes(dRaw),
Coeff: (&big.Int{}).SetBytes(tRaw),
})
}
}
}
return &pri, pub, nil
}
func rsaPublicFromMap(m map[string]interface{}) (*rsa.PublicKey, error) {
var pub rsa.PublicKey
if nStr, _ := m["n"].(string); nStr == "" {
return nil, erro.New("no n")
} else if nRaw, err := base64.RawURLEncoding.DecodeString(nStr); err != nil {
return nil, erro.Wrap(err)
} else if eStr, _ := m["e"].(string); eStr == "" {
return nil, erro.New("no e")
} else if eRaw, err := base64.RawURLEncoding.DecodeString(eStr); err != nil {
return nil, erro.Wrap(err)
} else {
pub.N = (&big.Int{}).SetBytes(nRaw)
pub.E = int((&big.Int{}).SetBytes(eRaw).Int64())
}
return &pub, nil
}
func commonFromMap(m map[string]interface{}) ([]byte, error) {
if kStr, _ := m["k"].(string); kStr == "" {
return nil, erro.New("no k")
} else {
return base64.RawURLEncoding.DecodeString(kStr)
}
}
func (this *keyImpl) Type() string { return this.kty }
func (this *keyImpl) Use() string { return this.use }
func (this *keyImpl) Operations() map[string]bool { return this.ops }
func (this *keyImpl) Algorithm() string { return this.alg }
func (this *keyImpl) Id() string { return this.id }
func (this *keyImpl) Public() crypto.PublicKey { return this.pub }
func (this *keyImpl) Private() crypto.PrivateKey { return this.pri }
func (this *keyImpl) Common() []byte { return this.com }
func (this *keyImpl) ToMap() map[string]interface{} {
m := map[string]interface{}{
tagKty: this.kty,
}
if this.use != "" {
m[tagUse] = this.use
}
if len(this.ops) > 0 {
ops := []interface{}{}
for op := range this.ops {
ops = append(ops, op)
}
m[tagKey_ops] = ops
}
if this.alg != "" {
m[tagAlg] = this.alg
}
if this.id != "" {
m[tagKid] = this.id
}
switch this.kty {
case tagEc:
if this.pri != nil {
return ecToMap(this.pri.(*ecdsa.PrivateKey), m)
} else {
return ecPublicToMap(this.pub.(*ecdsa.PublicKey), m)
}
case tagRsa:
if this.pri != nil {
return rsaToMap(this.pri.(*rsa.PrivateKey), m)
} else {
return rsaPublicToMap(this.pub.(*rsa.PublicKey), m)
}
case tagOct:
return commonToMap(this.com, m)
default:
return nil
}
}
func rsaToMap(key *rsa.PrivateKey, m map[string]interface{}) map[string]interface{} {
m = rsaPublicToMap(&key.PublicKey, m)
m["d"] = base64.RawURLEncoding.EncodeToString(key.D.Bytes())
m["p"] = base64.RawURLEncoding.EncodeToString(key.Primes[0].Bytes())
m["q"] = base64.RawURLEncoding.EncodeToString(key.Primes[1].Bytes())
m["dp"] = base64.RawURLEncoding.EncodeToString(key.Precomputed.Dp.Bytes())
m["dq"] = base64.RawURLEncoding.EncodeToString(key.Precomputed.Dq.Bytes())
m["qi"] = base64.RawURLEncoding.EncodeToString(key.Precomputed.Qinv.Bytes())
if len(key.Precomputed.CRTValues) > 0 {
var crts []map[string]interface{}
for _, crt := range key.Precomputed.CRTValues {
crts = append(crts, map[string]interface{}{
"r": base64.RawURLEncoding.EncodeToString(crt.R.Bytes()),
"d": base64.RawURLEncoding.EncodeToString(crt.Exp.Bytes()),
"t": base64.RawURLEncoding.EncodeToString(crt.Coeff.Bytes()),
})
}
m[tagOth] = crts
}
return m
}
func rsaPublicToMap(key *rsa.PublicKey, m map[string]interface{}) map[string]interface{} {
m["n"] = base64.RawURLEncoding.EncodeToString(key.N.Bytes())
m["e"] = base64.RawURLEncoding.EncodeToString(big.NewInt(int64(key.E)).Bytes())
return m
}
func ecToMap(key *ecdsa.PrivateKey, m map[string]interface{}) map[string]interface{} {
m = ecPublicToMap(&key.PublicKey, m)
size := (key.Params().BitSize + 7) / 8
m["d"] = base64.RawURLEncoding.EncodeToString(pad0(key.D.Bytes(), size))
return m
}
func ecPublicToMap(key *ecdsa.PublicKey, m map[string]interface{}) map[string]interface{} {
switch key.Params().BitSize {
case 256:
m[tagCrv] = tagP_256
case 384:
m[tagCrv] = tagP_384
case 521:
m[tagCrv] = tagP_521
default:
return nil
}
size := (key.Params().BitSize + 7) / 8
m["x"] = base64.RawURLEncoding.EncodeToString(pad0(key.X.Bytes(), size))
m["y"] = base64.RawURLEncoding.EncodeToString(pad0(key.Y.Bytes(), size))
return m
}
func commonToMap(key []byte, m map[string]interface{}) map[string]interface{} {
m["k"] = base64.RawURLEncoding.EncodeToString(key)
return m
}
// size バイトになるように前に 0 を詰める。
func pad0(b []byte, size int) []byte {
if len(b) < size {
buff := make([]byte, size)
copy(buff[size-len(b):], b)
b = buff
}
return b
}