Debian Codegraph @

jwk.go

raw symbols SCIP
1 /*-
2 * Copyright 2014 Square Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package jose
18
19 import (
20 "crypto"
21 "crypto/ecdsa"
22 "crypto/elliptic"
23 "crypto/rsa"
24 "crypto/x509"
25 "encoding/base64"
26 "errors"
27 "fmt"
28 "math/big"
29 "reflect"
30 "strings"
31
32 "gopkg.in/square/go-jose.v1/json"
33 )
34
35 // rawJsonWebKey represents a public or private key in JWK format, used for parsing/serializing.
36 type rawJsonWebKey struct {
37 Use string `json:"use,omitempty"`
38 Kty string `json:"kty,omitempty"`
39 Kid string `json:"kid,omitempty"`
40 Crv string `json:"crv,omitempty"`
41 Alg string `json:"alg,omitempty"`
42 K *byteBuffer `json:"k,omitempty"`
43 X *byteBuffer `json:"x,omitempty"`
44 Y *byteBuffer `json:"y,omitempty"`
45 N *byteBuffer `json:"n,omitempty"`
46 E *byteBuffer `json:"e,omitempty"`
47 // -- Following fields are only used for private keys --
48 // RSA uses D, P and Q, while ECDSA uses only D. Fields Dp, Dq, and Qi are
49 // completely optional. Therefore for RSA/ECDSA, D != nil is a contract that
50 // we have a private key whereas D == nil means we have only a public key.
51 D *byteBuffer `json:"d,omitempty"`
52 P *byteBuffer `json:"p,omitempty"`
53 Q *byteBuffer `json:"q,omitempty"`
54 Dp *byteBuffer `json:"dp,omitempty"`
55 Dq *byteBuffer `json:"dq,omitempty"`
56 Qi *byteBuffer `json:"qi,omitempty"`
57 // Certificates
58 X5c []string `json:"x5c,omitempty"`
59 }
60
61 // JsonWebKey represents a public or private key in JWK format.
62 type JsonWebKey struct {
63 Key interface{}
64 Certificates []*x509.Certificate
65 KeyID string
66 Algorithm string
67 Use string
68 }
69
70 // MarshalJSON serializes the given key to its JSON representation.
71 func (k JsonWebKey) MarshalJSON() ([]byte, error) {
72 var raw *rawJsonWebKey
73 var err error
74
75 switch key := k.Key.(type) {
76 case *ecdsa.PublicKey:
77 raw, err = fromEcPublicKey(key)
78 case *rsa.PublicKey:
79 raw = fromRsaPublicKey(key)
80 case *ecdsa.PrivateKey:
81 raw, err = fromEcPrivateKey(key)
82 case *rsa.PrivateKey:
83 raw, err = fromRsaPrivateKey(key)
84 case []byte:
85 raw, err = fromSymmetricKey(key)
86 default:
87 return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key))
88 }
89
90 if err != nil {
91 return nil, err
92 }
93
94 raw.Kid = k.KeyID
95 raw.Alg = k.Algorithm
96 raw.Use = k.Use
97
98 for _, cert := range k.Certificates {
99 raw.X5c = append(raw.X5c, base64.StdEncoding.EncodeToString(cert.Raw))
100 }
101
102 return json.Marshal(raw)
103 }
104
105 // UnmarshalJSON reads a key from its JSON representation.
106 func (k *JsonWebKey) UnmarshalJSON(data []byte) (err error) {
107 var raw rawJsonWebKey
108 err = json.Unmarshal(data, &raw)
109 if err != nil {
110 return err
111 }
112
113 var key interface{}
114 switch raw.Kty {
115 case "EC":
116 if raw.D != nil {
117 key, err = raw.ecPrivateKey()
118 } else {
119 key, err = raw.ecPublicKey()
120 }
121 case "RSA":
122 if raw.D != nil {
123 key, err = raw.rsaPrivateKey()
124 } else {
125 key, err = raw.rsaPublicKey()
126 }
127 case "oct":
128 key, err = raw.symmetricKey()
129 default:
130 err = fmt.Errorf("square/go-jose: unknown json web key type '%s'", raw.Kty)
131 }
132
133 if err == nil {
134 *k = JsonWebKey{Key: key, KeyID: raw.Kid, Algorithm: raw.Alg, Use: raw.Use}
135 }
136
137 k.Certificates = make([]*x509.Certificate, len(raw.X5c))
138 for i, cert := range raw.X5c {
139 raw, err := base64.StdEncoding.DecodeString(cert)
140 if err != nil {
141 return err
142 }
143 k.Certificates[i], err = x509.ParseCertificate(raw)
144 if err != nil {
145 return err
146 }
147 }
148
149 return
150 }
151
152 // JsonWebKeySet represents a JWK Set object.
153 type JsonWebKeySet struct {
154 Keys []JsonWebKey `json:"keys"`
155 }
156
157 // Key convenience method returns keys by key ID. Specification states
158 // that a JWK Set "SHOULD" use distinct key IDs, but allows for some
159 // cases where they are not distinct. Hence method returns a slice
160 // of JsonWebKeys.
161 func (s *JsonWebKeySet) Key(kid string) []JsonWebKey {
162 var keys []JsonWebKey
163 for _, key := range s.Keys {
164 if key.KeyID == kid {
165 keys = append(keys, key)
166 }
167 }
168
169 return keys
170 }
171
172 const rsaThumbprintTemplate = `{"e":"%s","kty":"RSA","n":"%s"}`
173 const ecThumbprintTemplate = `{"crv":"%s","kty":"EC","x":"%s","y":"%s"}`
174
175 func ecThumbprintInput(curve elliptic.Curve, x, y *big.Int) (string, error) {
176 coordLength := curveSize(curve)
177 crv, err := curveName(curve)
178 if err != nil {
179 return "", err
180 }
181
182 if len(x.Bytes()) > coordLength || len(y.Bytes()) > coordLength {
183 return "", errors.New("square/go-jose: invalid elliptic key (too large)")
184 }
185
186 return fmt.Sprintf(ecThumbprintTemplate, crv,
187 newFixedSizeBuffer(x.Bytes(), coordLength).base64(),
188 newFixedSizeBuffer(y.Bytes(), coordLength).base64()), nil
189 }
190
191 func rsaThumbprintInput(n *big.Int, e int) (string, error) {
192 return fmt.Sprintf(rsaThumbprintTemplate,
193 newBufferFromInt(uint64(e)).base64(),
194 newBuffer(n.Bytes()).base64()), nil
195 }
196
197 // Thumbprint computes the JWK Thumbprint of a key using the
198 // indicated hash algorithm.
199 func (k *JsonWebKey) Thumbprint(hash crypto.Hash) ([]byte, error) {
200 var input string
201 var err error
202 switch key := k.Key.(type) {
203 case *ecdsa.PublicKey:
204 input, err = ecThumbprintInput(key.Curve, key.X, key.Y)
205 case *ecdsa.PrivateKey:
206 input, err = ecThumbprintInput(key.Curve, key.X, key.Y)
207 case *rsa.PublicKey:
208 input, err = rsaThumbprintInput(key.N, key.E)
209 case *rsa.PrivateKey:
210 input, err = rsaThumbprintInput(key.N, key.E)
211 default:
212 return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key))
213 }
214
215 if err != nil {
216 return nil, err
217 }
218
219 h := hash.New()
220 h.Write([]byte(input))
221 return h.Sum(nil), nil
222 }
223
224 // IsPublic returns true if the JWK represents a public key (not symmetric, not private).
225 func (k *JsonWebKey) IsPublic() bool {
226 switch k.Key.(type) {
227 case *ecdsa.PublicKey, *rsa.PublicKey:
228 return true
229 default:
230 return false
231 }
232 }
233
234 // Valid checks that the key contains the expected parameters.
235 func (k *JsonWebKey) Valid() bool {
236 if k.Key == nil {
237 return false
238 }
239 switch key := k.Key.(type) {
240 case *ecdsa.PublicKey:
241 if key.Curve == nil || key.X == nil || key.Y == nil {
242 return false
243 }
244 case *ecdsa.PrivateKey:
245 if key.Curve == nil || key.X == nil || key.Y == nil || key.D == nil {
246 return false
247 }
248 case *rsa.PublicKey:
249 if key.N == nil || key.E == 0 {
250 return false
251 }
252 case *rsa.PrivateKey:
253 if key.N == nil || key.E == 0 || key.D == nil || len(key.Primes) < 2 {
254 return false
255 }
256 default:
257 return false
258 }
259 return true
260 }
261
262 func (key rawJsonWebKey) rsaPublicKey() (*rsa.PublicKey, error) {
263 if key.N == nil || key.E == nil {
264 return nil, fmt.Errorf("square/go-jose: invalid RSA key, missing n/e values")
265 }
266
267 return &rsa.PublicKey{
268 N: key.N.bigInt(),
269 E: key.E.toInt(),
270 }, nil
271 }
272
273 func fromRsaPublicKey(pub *rsa.PublicKey) *rawJsonWebKey {
274 return &rawJsonWebKey{
275 Kty: "RSA",
276 N: newBuffer(pub.N.Bytes()),
277 E: newBufferFromInt(uint64(pub.E)),
278 }
279 }
280
281 func (key rawJsonWebKey) ecPublicKey() (*ecdsa.PublicKey, error) {
282 var curve elliptic.Curve
283 switch key.Crv {
284 case "P-256":
285 curve = elliptic.P256()
286 case "P-384":
287 curve = elliptic.P384()
288 case "P-521":
289 curve = elliptic.P521()
290 default:
291 return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv)
292 }
293
294 if key.X == nil || key.Y == nil {
295 return nil, errors.New("square/go-jose: invalid EC key, missing x/y values")
296 }
297
298 x := key.X.bigInt()
299 y := key.Y.bigInt()
300
301 if !curve.IsOnCurve(x, y) {
302 return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve")
303 }
304
305 return &ecdsa.PublicKey{
306 Curve: curve,
307 X: x,
308 Y: y,
309 }, nil
310 }
311
312 func fromEcPublicKey(pub *ecdsa.PublicKey) (*rawJsonWebKey, error) {
313 if pub == nil || pub.X == nil || pub.Y == nil {
314 return nil, fmt.Errorf("square/go-jose: invalid EC key (nil, or X/Y missing)")
315 }
316
317 name, err := curveName(pub.Curve)
318 if err != nil {
319 return nil, err
320 }
321
322 size := curveSize(pub.Curve)
323
324 xBytes := pub.X.Bytes()
325 yBytes := pub.Y.Bytes()
326
327 if len(xBytes) > size || len(yBytes) > size {
328 return nil, fmt.Errorf("square/go-jose: invalid EC key (X/Y too large)")
329 }
330
331 key := &rawJsonWebKey{
332 Kty: "EC",
333 Crv: name,
334 X: newFixedSizeBuffer(xBytes, size),
335 Y: newFixedSizeBuffer(yBytes, size),
336 }
337
338 return key, nil
339 }
340
341 func (key rawJsonWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
342 var missing []string
343 switch {
344 case key.N == nil:
345 missing = append(missing, "N")
346 case key.E == nil:
347 missing = append(missing, "E")
348 case key.D == nil:
349 missing = append(missing, "D")
350 case key.P == nil:
351 missing = append(missing, "P")
352 case key.Q == nil:
353 missing = append(missing, "Q")
354 }
355
356 if len(missing) > 0 {
357 return nil, fmt.Errorf("square/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", "))
358 }
359
360 rv := &rsa.PrivateKey{
361 PublicKey: rsa.PublicKey{
362 N: key.N.bigInt(),
363 E: key.E.toInt(),
364 },
365 D: key.D.bigInt(),
366 Primes: []*big.Int{
367 key.P.bigInt(),
368 key.Q.bigInt(),
369 },
370 }
371
372 if key.Dp != nil {
373 rv.Precomputed.Dp = key.Dp.bigInt()
374 }
375 if key.Dq != nil {
376 rv.Precomputed.Dq = key.Dq.bigInt()
377 }
378 if key.Qi != nil {
379 rv.Precomputed.Qinv = key.Qi.bigInt()
380 }
381
382 err := rv.Validate()
383 return rv, err
384 }
385
386 func fromRsaPrivateKey(rsa *rsa.PrivateKey) (*rawJsonWebKey, error) {
387 if len(rsa.Primes) != 2 {
388 return nil, ErrUnsupportedKeyType
389 }
390
391 raw := fromRsaPublicKey(&rsa.PublicKey)
392
393 raw.D = newBuffer(rsa.D.Bytes())
394 raw.P = newBuffer(rsa.Primes[0].Bytes())
395 raw.Q = newBuffer(rsa.Primes[1].Bytes())
396
397 return raw, nil
398 }
399
400 func (key rawJsonWebKey) ecPrivateKey() (*ecdsa.PrivateKey, error) {
401 var curve elliptic.Curve
402 switch key.Crv {
403 case "P-256":
404 curve = elliptic.P256()
405 case "P-384":
406 curve = elliptic.P384()
407 case "P-521":
408 curve = elliptic.P521()
409 default:
410 return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv)
411 }
412
413 if key.X == nil || key.Y == nil || key.D == nil {
414 return nil, fmt.Errorf("square/go-jose: invalid EC private key, missing x/y/d values")
415 }
416
417 x := key.X.bigInt()
418 y := key.Y.bigInt()
419
420 if !curve.IsOnCurve(x, y) {
421 return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve")
422 }
423
424 return &ecdsa.PrivateKey{
425 PublicKey: ecdsa.PublicKey{
426 Curve: curve,
427 X: x,
428 Y: y,
429 },
430 D: key.D.bigInt(),
431 }, nil
432 }
433
434 func fromEcPrivateKey(ec *ecdsa.PrivateKey) (*rawJsonWebKey, error) {
435 raw, err := fromEcPublicKey(&ec.PublicKey)
436 if err != nil {
437 return nil, err
438 }
439
440 if ec.D == nil {
441 return nil, fmt.Errorf("square/go-jose: invalid EC private key")
442 }
443
444 raw.D = newBuffer(ec.D.Bytes())
445
446 return raw, nil
447 }
448
449 func fromSymmetricKey(key []byte) (*rawJsonWebKey, error) {
450 return &rawJsonWebKey{
451 Kty: "oct",
452 K: newBuffer(key),
453 }, nil
454 }
455
456 func (key rawJsonWebKey) symmetricKey() ([]byte, error) {
457 if key.K == nil {
458 return nil, fmt.Errorf("square/go-jose: invalid OCT (symmetric) key, missing k value")
459 }
460 return key.K.bytes(), nil
461 }