Debian Codegraph @

README.md

raw
1 # Golang (GO) Javascript Object Signing and Encryption (JOSE) and JSON Web Token (JWT) implementation
2
3 [![GoDoc](https://godoc.org/github.com/dvsekhvalnov/jose2go?status.svg)](http://godoc.org/github.com/dvsekhvalnov/jose2go)
4
5 Pure Golang (GO) library for generating, decoding and encrypting [JSON Web Tokens](https://tools.ietf.org/html/rfc7519). Zero dependency, relies only
6 on standard library.
7
8 Supports full suite of signing, encryption and compression algorithms defined by [JSON Web Algorithms](https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-31) as of July 4, 2014 version.
9
10 Extensively unit tested and cross tested (100+ tests) for compatibility with [jose.4.j](https://bitbucket.org/b_c/jose4j/wiki/Home), [Nimbus-JOSE-JWT](https://bitbucket.org/nimbusds/nimbus-jose-jwt/wiki/Home), [json-jwt](https://github.com/nov/json-jwt) and
11 [jose-jwt](https://github.com/dvsekhvalnov/jose-jwt) libraries.
12
13
14 ## Status
15 Used in production. GA ready. Current version is 1.9.
16
17 ## Important
18 v1.11 more security hardening, [ECDH-ES malformed ephemeral public key (`epk.x`) causes nil-curve dereference panic (remote DoS)](https://github.com/dvsekhvalnov/jose2go/security/advisories/GHSA-f24c-mccr-j77x)
19 v1.10 more security hardening, [#42](https://github.com/dvsekhvalnov/jose2go/issues/42)
20
21 v1.9 security hardening, fixed found vulnerabilities
22
23 v1.8 added experimental RSA-OAEP-384 and RSA-OAEP-512 key management algorithms
24
25 v1.7 introduced deflate decompression memory limits to avoid denial-of-service attacks aka 'deflate-bomb'. See [Customizing compression](#customizing-compression) section for details.
26
27 v1.6 security tuning options
28
29 v1.5 bug fix release
30
31 v1.4 changes default behavior of inserting `typ=JWT` header if not overriden. As of 1.4 no
32 extra headers added by library automatically. To mimic pre 1.4 behaviour use:
33 ```Go
34 token, err := jose.Sign(..., jose.Header("typ", "JWT"))
35
36 //or
37
38 token, err := jose.Encrypt(..., jose.Header("typ", "JWT"))
39 ```
40
41 v1.3 fixed potential Invalid Curve Attack on NIST curves within ECDH key management.
42 Upgrade strongly recommended.
43
44 v1.2 breaks `jose.Decode` interface by returning 3 values instead of 2.
45
46 v1.2 deprecates `jose.Compress` method in favor of using configuration options to `jose.Encrypt`,
47 the method will be removed in next release.
48
49 ### Migration to v1.2
50 Pre v1.2 decoding:
51
52 ```Go
53 payload,err := jose.Decode(token,sharedKey)
54 ```
55
56 Should be updated to v1.2:
57
58 ```Go
59 payload, headers, err := jose.Decode(token,sharedKey)
60 ```
61
62 Pre v1.2 compression:
63
64 ```Go
65 token,err := jose.Compress(payload,jose.DIR,jose.A128GCM,jose.DEF, key)
66 ```
67
68 Should be update to v1.2:
69
70 ```Go
71 token, err := jose.Encrypt(payload, jose.DIR, jose.A128GCM, key, jose.Zip(jose.DEF))
72 ```
73
74 ## Supported JWA algorithms
75
76 **Signing**
77 - HMAC signatures with HS256, HS384 and HS512.
78 - RSASSA-PKCS1-V1_5 signatures with RS256, RS384 and RS512.
79 - RSASSA-PSS signatures (probabilistic signature scheme with appendix) with PS256, PS384 and PS512.
80 - ECDSA signatures with ES256, ES384 and ES512.
81 - NONE (unprotected) plain text algorithm without integrity protection
82
83 **Encryption**
84 - RSAES OAEP (using SHA-1 and MGF1 with SHA-1) encryption with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
85 - RSAES OAEP 256, 384, 512 (using SHA-256, 384, 512 and MGF1 with SHA-256, 384, 512) encryption with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
86 - RSAES-PKCS1-V1_5 encryption with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
87 - A128KW, A192KW, A256KW encryption with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
88 - A128GCMKW, A192GCMKW, A256GCMKW encryption with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
89 - ECDH-ES with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
90 - ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
91 - PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW with A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM, A256GCM
92 - Direct symmetric key encryption with pre-shared key A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM and A256GCM
93
94 **Compression**
95 - DEFLATE compression
96
97 ## Installation
98 ### Grab package from github
99 `go get github.com/dvsekhvalnov/jose2go` or `go get -u github.com/dvsekhvalnov/jose2go` to update to latest version
100
101 ### Import package
102 ```Go
103 import (
104 "github.com/dvsekhvalnov/jose2go"
105 )
106 ```
107
108 ## Usage
109 #### Creating Plaintext (unprotected) Tokens
110
111 ```Go
112 package main
113
114 import (
115 "fmt"
116 "github.com/dvsekhvalnov/jose2go"
117 )
118
119 func main() {
120
121 payload := `{"hello": "world"}`
122
123 token,err := jose.Sign(payload,jose.NONE, nil)
124
125 if(err==nil) {
126 //go use token
127 fmt.Printf("\nPlaintext = %v\n",token)
128 }
129 }
130 ```
131
132 ### Creating signed tokens
133 #### HS-256, HS-384 and HS-512
134 Signing with HS256, HS384, HS512 expecting `[]byte` array key of corresponding length:
135
136 ```Go
137 package main
138
139 import (
140 "fmt"
141 "github.com/dvsekhvalnov/jose2go"
142 )
143
144 func main() {
145
146 payload := `{"hello": "world"}`
147
148 key := []byte{97,48,97,50,97,98,100,56,45,54,49,54,50,45,52,49,99,51,45,56,51,100,54,45,49,99,102,53,53,57,98,52,54,97,102,99}
149
150 token,err := jose.Sign(payload,jose.HS256,key)
151
152 if(err==nil) {
153 //go use token
154 fmt.Printf("\nHS256 = %v\n",token)
155 }
156 }
157 ```
158
159 #### RS-256, RS-384 and RS-512, PS-256, PS-384 and PS-512
160 Signing with RS256, RS384, RS512, PS256, PS384, PS512 expecting `*rsa.PrivateKey` private key of corresponding length. **jose2go** [provides convenient utils](#dealing-with-keys) to construct `*rsa.PrivateKey` instance from PEM encoded PKCS1 or PKCS8 data: `Rsa.ReadPrivate([]byte)` under `jose2go/keys/rsa` package.
161
162 ```Go
163 package main
164
165 import (
166 "fmt"
167 "io/ioutil"
168 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
169 "github.com/dvsekhvalnov/jose2go"
170 )
171
172 func main() {
173
174 payload := `{"hello": "world"}`
175
176 keyBytes,err := ioutil.ReadFile("private.key")
177
178 if(err!=nil) {
179 panic("invalid key file")
180 }
181
182 privateKey,e:=Rsa.ReadPrivate(keyBytes)
183
184 if(e!=nil) {
185 panic("invalid key format")
186 }
187
188 token,err := jose.Sign(payload,jose.RS256, privateKey)
189
190 if(err==nil) {
191 //go use token
192 fmt.Printf("\nRS256 = %v\n",token)
193 }
194 }
195 ```
196
197 #### ES-256, ES-384 and ES-512
198 ES256, ES384, ES512 ECDSA signatures expecting `*ecdsa.PrivateKey` private elliptic curve key of corresponding length. **jose2go** [provides convenient utils](#dealing-with-keys) to construct `*ecdsa.PrivateKey` instance from PEM encoded PKCS1 or PKCS8 data: `ecc.ReadPrivate([]byte)` or directly from `X,Y,D` parameters: `ecc.NewPrivate(x,y,d []byte)` under `jose2go/keys/ecc` package.
199
200 ```Go
201 package main
202
203 import (
204 "fmt"
205 "github.com/dvsekhvalnov/jose2go/keys/ecc"
206 "github.com/dvsekhvalnov/jose2go"
207 )
208
209 func main() {
210
211 payload := `{"hello":"world"}`
212
213 privateKey:=ecc.NewPrivate([]byte{4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9},
214 []byte{131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53},
215 []byte{ 42, 148, 231, 48, 225, 196, 166, 201, 23, 190, 229, 199, 20, 39, 226, 70, 209, 148, 29, 70, 125, 14, 174, 66, 9, 198, 80, 251, 95, 107, 98, 206 })
216
217 token,err := jose.Sign(payload, jose.ES256, privateKey)
218
219 if(err==nil) {
220 //go use token
221 fmt.Printf("\ntoken = %v\n",token)
222 }
223 }
224 ```
225
226 ### Creating encrypted tokens
227 #### RSA-OAEP-512, RSA-OAEP-384, RSA-OAEP-256, RSA-OAEP and RSA1\_5 key management algorithm
228 RSA-OAEP-512, RSA-OAEP-384, RSA-OAEP-256, RSA-OAEP and RSA1_5 key management expecting `*rsa.PublicKey` public key of corresponding length.
229
230 ```Go
231 package main
232
233 import (
234 "fmt"
235 "io/ioutil"
236 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
237 "github.com/dvsekhvalnov/jose2go"
238 )
239
240 func main() {
241
242 payload := `{"hello": "world"}`
243
244 keyBytes,err := ioutil.ReadFile("public.key")
245
246 if(err!=nil) {
247 panic("invalid key file")
248 }
249
250 publicKey,e:=Rsa.ReadPublic(keyBytes)
251
252 if(e!=nil) {
253 panic("invalid key format")
254 }
255
256 //OR:
257 //token,err := jose.Encrypt(payload, jose.RSA1_5, jose.A256GCM, publicKey)
258 token,err := jose.Encrypt(payload, jose.RSA_OAEP, jose.A256GCM, publicKey)
259
260 if(err==nil) {
261 //go use token
262 fmt.Printf("\ntoken = %v\n",token)
263 }
264 }
265 ```
266
267 #### AES Key Wrap key management family of algorithms
268 AES128KW, AES192KW and AES256KW key management requires `[]byte` array key of corresponding length
269
270 ```Go
271 package main
272
273 import (
274 "fmt"
275 "github.com/dvsekhvalnov/jose2go"
276 )
277
278 func main() {
279
280 payload := `{"hello": "world"}`
281
282 sharedKey :=[]byte{194,164,235,6,138,248,171,239,24,216,11,22,137,199,215,133}
283
284 token,err := jose.Encrypt(payload,jose.A128KW,jose.A128GCM,sharedKey)
285
286 if(err==nil) {
287 //go use token
288 fmt.Printf("\nA128KW A128GCM = %v\n",token)
289 }
290 }
291 ```
292
293 #### AES GCM Key Wrap key management family of algorithms
294 AES128GCMKW, AES192GCMKW and AES256GCMKW key management requires `[]byte` array key of corresponding length
295
296 ```Go
297 package main
298
299 import (
300 "fmt"
301 "github.com/dvsekhvalnov/jose2go"
302 )
303
304 func main() {
305
306 payload := `{"hello": "world"}`
307
308 sharedKey :=[]byte{194,164,235,6,138,248,171,239,24,216,11,22,137,199,215,133}
309
310 token,err := jose.Encrypt(payload,jose.A128GCMKW,jose.A128GCM,sharedKey)
311
312 if(err==nil) {
313 //go use token
314 fmt.Printf("\nA128GCMKW A128GCM = %v\n",token)
315 }
316 }
317 ```
318
319 #### ECDH-ES and ECDH-ES with AES Key Wrap key management family of algorithms
320 ECDH-ES and ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW key management requires `*ecdsa.PublicKey` elliptic curve key of corresponding length. **jose2go** [provides convenient utils](#dealing-with-keys) to construct `*ecdsa.PublicKey` instance from PEM encoded PKCS1 X509 certificate or PKIX data: `ecc.ReadPublic([]byte)` or directly from `X,Y` parameters: `ecc.NewPublic(x,y []byte)`under `jose2go/keys/ecc` package:
321
322 ```Go
323 package main
324
325 import (
326 "fmt"
327 "github.com/dvsekhvalnov/jose2go/keys/ecc"
328 "github.com/dvsekhvalnov/jose2go"
329 )
330
331 func main() {
332
333 payload := `{"hello":"world"}`
334
335 publicKey:=ecc.NewPublic([]byte{4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9},
336 []byte{131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53})
337
338 token,err := jose.Encrypt(payload, jose.ECDH_ES, jose.A128CBC_HS256, publicKey)
339
340 if(err==nil) {
341 //go use token
342 fmt.Printf("\ntoken = %v\n",token)
343 }
344 }
345 ```
346
347 #### PBES2 using HMAC SHA with AES Key Wrap key management family of algorithms
348 PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW key management requires `string` passphrase from which actual key will be derived
349
350 ```Go
351 package main
352
353 import (
354 "fmt"
355 "github.com/dvsekhvalnov/jose2go"
356 )
357
358 func main() {
359
360 payload := `{"hello": "world"}`
361
362 passphrase := `top secret`
363
364 token,err := jose.Encrypt(payload,jose.PBES2_HS256_A128KW,jose.A256GCM,passphrase)
365
366 if(err==nil) {
367 //go use token
368 fmt.Printf("\nPBES2_HS256_A128KW A256GCM = %v\n",token)
369 }
370 }
371 ```
372
373 #### DIR direct pre-shared symmetric key management
374 Direct key management with pre-shared symmetric keys expecting `[]byte` array key of corresponding length:
375
376 ```Go
377 package main
378
379 import (
380 "fmt"
381 "github.com/dvsekhvalnov/jose2go"
382 )
383
384 func main() {
385
386 payload := `{"hello": "world"}`
387
388 sharedKey :=[]byte{194,164,235,6,138,248,171,239,24,216,11,22,137,199,215,133}
389
390 token,err := jose.Encrypt(payload,jose.DIR,jose.A128GCM,sharedKey)
391
392 if(err==nil) {
393 //go use token
394 fmt.Printf("\nDIR A128GCM = %v\n",token)
395 }
396 }
397 ```
398
399 ### Creating compressed & encrypted tokens
400 #### DEFLATE compression
401 **jose2go** supports optional DEFLATE compression of payload before encrypting, can be used with all supported encryption and key management algorithms:
402
403 ```Go
404 package main
405
406 import (
407 "fmt"
408 "github.com/dvsekhvalnov/jose2go"
409 )
410
411 func main() {
412
413 payload := `{"hello": "world"}`
414
415 sharedKey := []byte{194, 164, 235, 6, 138, 248, 171, 239, 24, 216, 11, 22, 137, 199, 215, 133}
416
417 token, err := jose.Encrypt(payload, jose.DIR, jose.A128GCM, sharedKey, jose.Zip(jose.DEF))
418
419 if err == nil {
420 //go use token
421 fmt.Printf("\nDIR A128GCM DEFLATED= %v\n", token)
422 }
423 }
424 ```
425
426 ### Verifying, Decoding and Decompressing tokens
427 Decoding json web tokens is fully symmetric to creating signed or encrypted tokens (with respect to public/private cryptography), decompressing deflated payloads is handled automatically:
428
429 As of v1.2 decode method defined as `jose.Decode() payload string, headers map[string]interface{}, err error` and returns both payload as unprocessed string and headers as map.
430
431 **HS256, HS384, HS512** signatures, **A128KW, A192KW, A256KW**,**A128GCMKW, A192GCMKW, A256GCMKW** and **DIR** key management algorithm expecting `[]byte` array key:
432
433 ```Go
434 package main
435
436 import (
437 "fmt"
438 "github.com/dvsekhvalnov/jose2go"
439 )
440
441 func main() {
442
443 token := "eyJhbGciOiJIUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.chIoYWrQMA8XL5nFz6oLDJyvgHk2KA4BrFGrKymjC8E"
444
445 sharedKey :=[]byte{97,48,97,50,97,98,100,56,45,54,49,54,50,45,52,49,99,51,45,56,51,100,54,45,49,99,102,53,53,57,98,52,54,97,102,99}
446
447 payload, headers, err := jose.Decode(token,sharedKey)
448
449 if(err==nil) {
450 //go use token
451 fmt.Printf("\npayload = %v\n",payload)
452
453 //and/or use headers
454 fmt.Printf("\nheaders = %v\n",headers)
455 }
456 }
457 ```
458
459 **RS256, RS384, RS512**,**PS256, PS384, PS512** signatures expecting `*rsa.PublicKey` public key of corresponding length. **jose2go** [provides convenient utils](#dealing-with-keys) to construct `*rsa.PublicKey` instance from PEM encoded PKCS1 X509 certificate or PKIX data: `Rsa.ReadPublic([]byte)` under `jose2go/keys/rsa` package:
460
461 ```Go
462 package main
463
464 import (
465 "fmt"
466 "io/ioutil"
467 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
468 "github.com/dvsekhvalnov/jose2go"
469 )
470
471 func main() {
472
473 token := "eyJhbGciOiJSUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.NL_dfVpZkhNn4bZpCyMq5TmnXbT4yiyecuB6Kax_lV8Yq2dG8wLfea-T4UKnrjLOwxlbwLwuKzffWcnWv3LVAWfeBxhGTa0c4_0TX_wzLnsgLuU6s9M2GBkAIuSMHY6UTFumJlEeRBeiqZNrlqvmAzQ9ppJHfWWkW4stcgLCLMAZbTqvRSppC1SMxnvPXnZSWn_Fk_q3oGKWw6Nf0-j-aOhK0S0Lcr0PV69ZE4xBYM9PUS1MpMe2zF5J3Tqlc1VBcJ94fjDj1F7y8twmMT3H1PI9RozO-21R0SiXZ_a93fxhE_l_dj5drgOek7jUN9uBDjkXUwJPAyp9YPehrjyLdw"
474
475 keyBytes, err := ioutil.ReadFile("public.key")
476
477 if(err!=nil) {
478 panic("invalid key file")
479 }
480
481 publicKey, e:=Rsa.ReadPublic(keyBytes)
482
483 if(e!=nil) {
484 panic("invalid key format")
485 }
486
487 payload, headers, err := jose.Decode(token, publicKey)
488
489 if(err==nil) {
490 //go use token
491 fmt.Printf("\npayload = %v\n",payload)
492
493 //and/or use headers
494 fmt.Printf("\nheaders = %v\n",headers)
495 }
496 }
497 ```
498
499 **RSA-OAEP-512**, **RSA-OAEP-384** ,**RSA-OAEP-256**, **RSA-OAEP** and **RSA1_5** key management algorithms expecting `*rsa.PrivateKey` private key of corresponding length:
500
501 ```Go
502 package main
503
504 import (
505 "fmt"
506 "io/ioutil"
507 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
508 "github.com/dvsekhvalnov/jose2go"
509 )
510
511 func main() {
512
513 token := "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMjU2R0NNIn0.ixD3WVOkvaxeLKi0kyVqTzM6W2EW25SHHYCAr9473Xq528xSK0AVux6kUtv7QMkQKgkMvO8X4VdvonyGkDZTK2jgYUiI06dz7I1sjWJIbyNVrANbBsmBiwikwB-9DLEaKuM85Lwu6gnzbOF6B9R0428ckxmITCPDrzMaXwYZHh46FiSg9djChUTex0pHGhNDiEIgaINpsmqsOFX1L2Y7KM2ZR7wtpR3kidMV3JlxHdKheiPKnDx_eNcdoE-eogPbRGFdkhEE8Dyass1ZSxt4fP27NwsIer5pc0b922_3XWdi1r1TL_fLvGktHLvt6HK6IruXFHpU4x5Z2gTXWxEIog.zzTNmovBowdX2_hi.QSPSgXn0w25ugvzmu2TnhePn.0I3B9BE064HFNP2E0I7M9g"
514
515 keyBytes, err := ioutil.ReadFile("private.key")
516
517 if(err!=nil) {
518 panic("invalid key file")
519 }
520
521 privateKey, e:=Rsa.ReadPrivate(keyBytes)
522
523 if(e!=nil) {
524 panic("invalid key format")
525 }
526
527 payload, headers, err := jose.Decode(token, privateKey)
528
529 if(err==nil) {
530 //go use payload
531 fmt.Printf("\npayload = %v\n",payload)
532
533 //and/or use headers
534 fmt.Printf("\nheaders = %v\n",headers)
535 }
536 }
537 ```
538
539 **PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW** key management algorithms expects `string` passpharase as a key
540
541 ```Go
542 package main
543
544 import (
545 "fmt"
546 "github.com/dvsekhvalnov/jose2go"
547 )
548
549 func main() {
550
551 token := `eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJlbmMiOiJBMjU2R0NNIiwicDJjIjo4MTkyLCJwMnMiOiJlZWpFZTF0YmJVbU5XV2s2In0.J2HTgltxH3p7A2zDgQWpZPgA2CHTSnDmMhlZWeSOMoZ0YvhphCeg-w.FzYG5AOptknu7jsG.L8jAxfxZhDNIqb0T96YWoznQ.yNeOfQWUbm8KuDGZ_5lL_g`
552
553 passphrase := `top secret`
554
555 payload, headers, err := jose.Decode(token,passphrase)
556
557 if(err==nil) {
558 //go use token
559 fmt.Printf("\npayload = %v\n",payload)
560
561 //and/or use headers
562 fmt.Printf("\nheaders = %v\n",headers)
563 }
564 }
565 ```
566
567 **ES256, ES284, ES512** signatures expecting `*ecdsa.PublicKey` public elliptic curve key of corresponding length. **jose2go** [provides convenient utils](#dealing-with-keys) to construct `*ecdsa.PublicKey` instance from PEM encoded PKCS1 X509 certificate or PKIX data: `ecc.ReadPublic([]byte)` or directly from `X,Y` parameters: `ecc.NewPublic(x,y []byte)`under `jose2go/keys/ecc` package:
568
569 ```Go
570 package main
571
572 import (
573 "fmt"
574 "github.com/dvsekhvalnov/jose2go/keys/ecc"
575 "github.com/dvsekhvalnov/jose2go"
576 )
577
578 func main() {
579
580 token := "eyJhbGciOiJFUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.EVnmDMlz-oi05AQzts-R3aqWvaBlwVZddWkmaaHyMx5Phb2NSLgyI0kccpgjjAyo1S5KCB3LIMPfmxCX_obMKA"
581
582 publicKey:=ecc.NewPublic([]byte{4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9},
583 []byte{131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53})
584
585 payload, headers, err := jose.Decode(token, publicKey)
586
587 if(err==nil) {
588 //go use token
589 fmt.Printf("\npayload = %v\n",payload)
590
591 //and/or use headers
592 fmt.Printf("\nheaders = %v\n",headers)
593 }
594 }
595 ```
596
597 **ECDH-ES** and **ECDH-ES+A128KW**, **ECDH-ES+A192KW**, **ECDH-ES+A256KW** key management expecting `*ecdsa.PrivateKey` private elliptic curve key of corresponding length. **jose2go** [provides convenient utils](#dealing-with-keys) to construct `*ecdsa.PrivateKey` instance from PEM encoded PKCS1 or PKCS8 data: `ecc.ReadPrivate([]byte)` or directly from `X,Y,D` parameters: `ecc.NewPrivate(x,y,d []byte)` under `jose2go/keys/ecc` package:
598
599 ```Go
600 package main
601
602 import (
603 "fmt"
604 "github.com/dvsekhvalnov/jose2go/keys/ecc"
605 "github.com/dvsekhvalnov/jose2go"
606 )
607
608 func main() {
609
610 token := "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImVwayI6eyJrdHkiOiJFQyIsIngiOiItVk1LTG5NeW9IVHRGUlpGNnFXNndkRm5BN21KQkdiNzk4V3FVMFV3QVhZIiwieSI6ImhQQWNReTgzVS01Qjl1U21xbnNXcFZzbHVoZGJSZE1nbnZ0cGdmNVhXTjgiLCJjcnYiOiJQLTI1NiJ9fQ..UA3N2j-TbYKKD361AxlXUA.XxFur_nY1GauVp5W_KO2DEHfof5s7kUwvOgghiNNNmnB4Vxj5j8VRS8vMOb51nYy2wqmBb2gBf1IHDcKZdACkCOMqMIcpBvhyqbuKiZPLHiilwSgVV6ubIV88X0vK0C8ZPe5lEyRudbgFjdlTnf8TmsvuAsdtPn9dXwDjUR23bD2ocp8UGAV0lKqKzpAw528vTfD0gwMG8gt_op8yZAxqqLLljMuZdTnjofAfsW2Rq3Z6GyLUlxR51DAUlQKi6UpsKMJoXTrm1Jw8sXBHpsRqA.UHCYOtnqk4SfhAknCnymaQ"
611
612 privateKey:=ecc.NewPrivate([]byte{4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9},
613 []byte{131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53},
614 []byte{ 42, 148, 231, 48, 225, 196, 166, 201, 23, 190, 229, 199, 20, 39, 226, 70, 209, 148, 29, 70, 125, 14, 174, 66, 9, 198, 80, 251, 95, 107, 98, 206 })
615
616 payload, headers, err := jose.Decode(token, privateKey)
617
618 if(err==nil) {
619 //go use token
620 fmt.Printf("\npayload = %v\n",payload)
621
622 //and/or use headers
623 fmt.Printf("\nheaders = %v\n",headers)
624 }
625 }
626 ```
627
628 ### Adding extra headers
629 It's possible to pass additional headers while encoding token. **jose2go** provides convenience configuration helpers: `Header(name string, value interface{})` and `Headers(headers map[string]interface{})` that can be passed to `Sign(..)` and `Encrypt(..)` calls.
630
631 Note: **jose2go** do not allow to override `alg`, `enc` and `zip` headers.
632
633 Example of signing with extra headers:
634 ```Go
635 token, err := jose.Sign(payload, jose.ES256, key,
636 jose.Header("keyid", "111-222-333"),
637 jose.Header("trans-id", "aaa-bbb"))
638 ```
639
640 Encryption with extra headers:
641 ```Go
642 token, err := jose.Encrypt(payload, jose.DIR, jose.A128GCM, sharedKey,
643 jose.Headers(map[string]interface{}{"keyid": "111-22-33", "cty": "text/plain"}))
644 ```
645
646 ### Two phase validation
647 In some cases validation (decoding) key can be unknown prior to examining token content. For instance one can use different keys per token issuer or rely on headers information to determine which key to use, do logging or other things.
648
649 **jose2go** allows to pass `func(headers map[string]interface{}, payload string) key interface{}` callback instead of key to `jose.Decode(..)`. Callback will be executed prior to decoding and integrity validation and will recieve parsed headers and payload as is (for encrypted tokens it will be cipher text). Callback should return key to be used for actual decoding process or `error` if decoding should be stopped, given error object will be returned from `jose.Decode(..)` call.
650
651 Example of decoding token with callback:
652
653 ```Go
654 package main
655
656 import (
657 "crypto/rsa"
658 "fmt"
659 "github.com/dvsekhvalnov/jose2go"
660 "github.com/dvsekhvalnov/jose2go/keys/rsa"
661 "io/ioutil"
662 "errors"
663 )
664
665 func main() {
666
667 token := "eyJhbGciOiJSUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.NL_dfVpZkhNn4bZpCyMq5TmnXbT4yiyecuB6Kax_lV8Yq2dG8wLfea-T4UKnrjLOwxlbwLwuKzffWcnWv3LVAWfeBxhGTa0c4_0TX_wzLnsgLuU6s9M2GBkAIuSMHY6UTFumJlEeRBeiqZNrlqvmAzQ9ppJHfWWkW4stcgLCLMAZbTqvRSppC1SMxnvPXnZSWn_Fk_q3oGKWw6Nf0-j-aOhK0S0Lcr0PV69ZE4xBYM9PUS1MpMe2zF5J3Tqlc1VBcJ94fjDj1F7y8twmMT3H1PI9RozO-21R0SiXZ_a93fxhE_l_dj5drgOek7jUN9uBDjkXUwJPAyp9YPehrjyLdw"
668
669 payload, _, err := jose.Decode(token,
670 func(headers map[string]interface{}, payload string) interface{} {
671 //log something
672 fmt.Printf("\nHeaders before decoding: %v\n", headers)
673 fmt.Printf("\nPayload before decoding: %v\n", payload)
674
675 //lookup key based on keyid header as en example
676 //or lookup based on something from payload, e.g. 'iss' claim for instance
677 key := FindKey(headers['keyid'])
678
679 if(key==nil) {
680 return errors.New("Key not found")
681 }
682
683 return key;
684 })
685
686 if err == nil {
687 //go use token
688 fmt.Printf("\ndecoded payload = %v\n", payload)
689 }
690 }
691 ```
692
693 Two phase validation can be used for implementing additional things like strict `alg` or `enc` validation, see [Customizing library for security](#customizing-library-for-security) for more information.
694
695 ### Working with binary payload
696 In addition to work with string payloads (typical use-case) `jose2go` supports
697 encoding and decoding of raw binary data. `jose.DecodeBytes`, `jose.SignBytes`
698 and `jose.EncryptBytes` functions provides similar interface but accepting
699 `[]byte` payloads.
700
701 Examples:
702
703 ```Go
704 package main
705
706 import (
707 "github.com/dvsekhvalnov/jose2go"
708 )
709
710 func main() {
711
712 token := `eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJlbmMiOiJBMjU2R0NNIiwicDJjIjo4MTkyLCJwMnMiOiJlZWpFZTF0YmJVbU5XV2s2In0.J2HTgltxH3p7A2zDgQWpZPgA2CHTSnDmMhlZWeSOMoZ0YvhphCeg-w.FzYG5AOptknu7jsG.L8jAxfxZhDNIqb0T96YWoznQ.yNeOfQWUbm8KuDGZ_5lL_g`
713
714 passphrase := `top secret`
715
716 payload, headers, err := jose.DecodeBytes(token,passphrase)
717
718 if(err==nil) {
719 //go use token
720 //payload = []byte{....}
721 }
722 }
723 ```
724
725 ```Go
726 package main
727
728 import (
729 "fmt"
730 "io/ioutil"
731 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
732 "github.com/dvsekhvalnov/jose2go"
733 )
734
735 func main() {
736
737 payload := []byte {0x01, 0x02, 0x03, 0x04}
738
739 keyBytes,err := ioutil.ReadFile("private.key")
740
741 if(err!=nil) {
742 panic("invalid key file")
743 }
744
745 privateKey,e:=Rsa.ReadPrivate(keyBytes)
746
747 if(e!=nil) {
748 panic("invalid key format")
749 }
750
751 token,err := jose.SignBytes(payload,jose.RS256, privateKey)
752
753 if(err==nil) {
754 //go use token
755 fmt.Printf("\nRS256 = %v\n",token)
756 }
757 }
758 ```
759
760 ```Go
761 package main
762
763 import (
764 "fmt"
765 "io/ioutil"
766 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
767 "github.com/dvsekhvalnov/jose2go"
768 )
769
770 func main() {
771
772 payload := []byte {0x01, 0x02, 0x03, 0x04}
773
774 keyBytes,err := ioutil.ReadFile("public.key")
775
776 if(err!=nil) {
777 panic("invalid key file")
778 }
779
780 publicKey,e:=Rsa.ReadPublic(keyBytes)
781
782 if(e!=nil) {
783 panic("invalid key format")
784 }
785
786 token,err := jose.EncryptBytes(payload, jose.RSA_OAEP, jose.A256GCM, publicKey)
787
788 if(err==nil) {
789 //go use token
790 fmt.Printf("\ntoken = %v\n",token)
791 }
792 }
793 ```
794 ### Dealing with keys
795 **jose2go** provides several helper methods to simplify loading & importing of elliptic and rsa keys. Import `jose2go/keys/rsa` or `jose2go/keys/ecc` respectively:
796
797 #### RSA keys
798 1. `Rsa.ReadPrivate(raw []byte) (key *rsa.PrivateKey,err error)` attempts to parse RSA private key from PKCS1 or PKCS8 format (`BEGIN RSA PRIVATE KEY` and `BEGIN PRIVATE KEY` headers)
799
800 ```Go
801 package main
802
803 import (
804 "fmt"
805 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
806 "io/ioutil"
807 )
808
809 func main() {
810
811 keyBytes, _ := ioutil.ReadFile("private.key")
812
813 privateKey, err:=Rsa.ReadPrivate(keyBytes)
814
815 if(err!=nil) {
816 panic("invalid key format")
817 }
818
819 fmt.Printf("privateKey = %v\n",privateKey)
820 }
821 ```
822
823 2. `Rsa.ReadPublic(raw []byte) (key *rsa.PublicKey,err error)` attempts to parse RSA public key from PKIX key format or PKCS1 X509 certificate (`BEGIN PUBLIC KEY` and `BEGIN CERTIFICATE` headers)
824
825 ```Go
826 package main
827
828 import (
829 "fmt"
830 Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
831 "io/ioutil"
832 )
833
834 func main() {
835
836 keyBytes, _ := ioutil.ReadFile("public.cer")
837
838 publicKey, err:=Rsa.ReadPublic(keyBytes)
839
840 if(err!=nil) {
841 panic("invalid key format")
842 }
843
844 fmt.Printf("publicKey = %v\n",publicKey)
845 }
846 ```
847
848 #### ECC keys
849 1. `ecc.ReadPrivate(raw []byte) (key *ecdsa.PrivateKey,err error)` attemps to parse elliptic curve private key from PKCS1 or PKCS8 format (`BEGIN EC PRIVATE KEY` and `BEGIN PRIVATE KEY` headers)
850
851 ```Go
852 package main
853
854 import (
855 "fmt"
856 "github.com/dvsekhvalnov/jose2go/keys/ecc"
857 "io/ioutil"
858 )
859
860 func main() {
861
862 keyBytes, _ := ioutil.ReadFile("ec-private.pem")
863
864 ecPrivKey, err:=ecc.ReadPrivate(keyBytes)
865
866 if(err!=nil) {
867 panic("invalid key format")
868 }
869
870 fmt.Printf("ecPrivKey = %v\n",ecPrivKey)
871 }
872 ```
873
874 2. `ecc.ReadPublic(raw []byte) (key *ecdsa.PublicKey,err error)` attemps to parse elliptic curve public key from PKCS1 X509 or PKIX format (`BEGIN PUBLIC KEY` and `BEGIN CERTIFICATE` headers)
875
876 ```Go
877 package main
878
879 import (
880 "fmt"
881 "github.com/dvsekhvalnov/jose2go/keys/ecc"
882 "io/ioutil"
883 )
884
885 func main() {
886
887 keyBytes, _ := ioutil.ReadFile("ec-public.key")
888
889 ecPubKey, err:=ecc.ReadPublic(keyBytes)
890
891 if(err!=nil) {
892 panic("invalid key format")
893 }
894
895 fmt.Printf("ecPubKey = %v\n",ecPubKey)
896 }
897 ```
898
899 3. `ecc.NewPublic(x,y []byte) (*ecdsa.PublicKey)` constructs elliptic public key from (X,Y) represented as bytes. Supported are NIST curves P-256,P-384 and P-521. Curve detected automatically by input length.
900
901 ```Go
902 package main
903
904 import (
905 "fmt"
906 "github.com/dvsekhvalnov/jose2go/keys/ecc"
907 )
908
909 func main() {
910
911 ecPubKey:=ecc.NewPublic([]byte{4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9},
912 []byte{131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53})
913
914 fmt.Printf("ecPubKey = %v\n",ecPubKey)
915 }
916 ```
917
918 4. `ecc.NewPrivate(x,y,d []byte) (*ecdsa.PrivateKey)` constructs elliptic private key from (X,Y) and D represented as bytes. Supported are NIST curves P-256,P-384 and P-521. Curve detected automatically by input length.
919
920 ```Go
921 package main
922
923 import (
924 "fmt"
925 "github.com/dvsekhvalnov/jose2go/keys/ecc"
926 )
927
928 func main() {
929
930 ecPrivKey:=ecc.NewPrivate([]byte{4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9},
931 []byte{131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53},
932 []byte{ 42, 148, 231, 48, 225, 196, 166, 201, 23, 190, 229, 199, 20, 39, 226, 70, 209, 148, 29, 70, 125, 14, 174, 66, 9, 198, 80, 251, 95, 107, 98, 206 })
933
934 fmt.Printf("ecPrivKey = %v\n",ecPrivKey)
935 }
936 ```
937
938 ### More examples
939 Checkout `jose_test.go` for more examples.
940
941 ## Customizing library for security
942 In response to ever increasing attacks on various JWT implementations, `jose2go` as of version v1.6 introduced number of additional security controls to limit potential attack surface on services and projects using the library.
943
944 ### Deregister algorithm implementations
945 One can use following methods to deregister any signing, encryption, key management or compression algorithms from runtime suite, that is considered unsafe or simply not expected by service.
946
947 - `func DeregisterJwa(alg string) JwaAlgorithm`
948 - `func DeregisterJwe(alg string) JweEncryption`
949 - `func DeregisterJws(alg string) JwsAlgorithm`
950 - `func DeregisterJwc(alg string) JwcAlgorithm`
951
952 All of them expecting alg name matching `jose` constants and returns implementation that have been deregistered.
953
954 ### Strict validation
955 Sometimes it is desirable to verify that `alg` or `enc` values are matching expected before attempting to decode actual payload.
956 `jose2go` provides helper matchers to be used within [Two-phase validation](#two-phase-validation) precheck:
957
958 - `jose.Alg(key, alg)` - to match alg header
959 - `jose.Enc(key, alg)` - to match alg and enc headers
960
961 ```Go
962 token := "eyJhbGciOiJSUzI1NiIsImN0eSI6InRleHRcL3BsYWluIn0.eyJoZWxsbyI6ICJ3b3JsZCJ9.NL_dfVpZkhNn4bZpCyMq5TmnXbT4yiyecuB6Kax_lV8Yq2dG8wLfea-T4UKnrjLOwxlbwLwuKzffWcnWv3LVAWfeBxhGTa0c4_0TX_wzLnsgLuU6s9M2GBkAIuSMHY6UTFumJlEeRBeiqZNrlqvmAzQ9ppJHfWWkW4stcgLCLMAZbTqvRSppC1SMxnvPXnZSWn_Fk_q3oGKWw6Nf0-j-aOhK0S0Lcr0PV69ZE4xBYM9PUS1MpMe2zF5J3Tqlc1VBcJ94fjDj1F7y8twmMT3H1PI9RozO-21R0SiXZ_a93fxhE_l_dj5drgOek7jUN9uBDjkXUwJPAyp9YPehrjyLdw"
963
964 key := Rsa.ReadPublic(....)
965
966 // we expecting 'RS256' alg here and if matching continue to decode with a key
967 payload, header, err := jose.Decode(token, Alg(key, "RS256"))
968
969 // or match both alg and enc for decrypting scenarios
970 payload, header, err := jose.Decode(token, Enc(key, "RSA-OAEP-256", "A192CBC-HS384"))
971 ```
972
973 ### Customizing PBKDF2
974 As it quite easy to abuse PBES2 family of algorithms via forging header with extra large p2c values, jose-jwt library introduced iteration count limits in v1.6 to reduce runtime exposure.
975
976 By default, maxIterations is set according to [OWASP PBKDF2](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2) Recomendations:
977
978 ```
979 PBES2-HS256+A128KW: 1300000
980 PBES2-HS384+A192KW: 950000
981 PBES2-HS512+A256KW: 600000
982 ```
983
984 , while minIterations kept at 0 for backward compatibility.
985
986 If it is desired to implement different limits, register new implementation with new parameters:
987
988 ```Go
989 jose.RegisterJwa(NewPbse2HmacAesKWAlg(128, 1300000, 1300000))
990 jose.RegisterJwa(NewPbse2HmacAesKWAlg(192, 950000, 950000))
991 jose.RegisterJwa(NewPbse2HmacAesKWAlg(256, 600000, 600000))
992 ```
993
994 In case you can't upgrade to latest version, but would like to have protections against PBES2 abuse, it is recommended to stick with [Two-phase validation](#two-phase-validation) precheck before decoding:
995
996 ```Go
997 test, headers, err := Decode(token, func(headers map[string]interface{}, payload string) interface{} {
998 alg := headers["alg"].(string)
999 p2c := headers["p2c"].(float64)
1000
1001 if strings.HasPrefix(alg, "PBES2-") && int64(p2c) > 100 {
1002 return errors.New("Too many p2c interation count, aborting")
1003 }
1004
1005 return "top secret"
1006 })
1007 ```
1008
1009 ### Customizing compression
1010 There were denial-of-service attacks reported on JWT libraries that supports deflate compression by constructing malicious payload that explodes in terms of RAM on decompression. See for details: [#33](https://github.com/dvsekhvalnov/jose2go/issues/33)
1011
1012 As of v1.7.0 `jose2go` limits decompression buffer to 250Kb to limit memory consumption and additionaly provides a way to adjust the limit according to specific scenarios:
1013
1014 ```Go
1015 // Override compression alg with new limits (10Kb example)
1016 jose.RegisterJwc(RegisterJwc(NewDeflate(10240)))
1017 ```
1018
1019 ## Changelog
1020 ### 1.8
1021 - RSA-OAEP-384 and RSA-OAEP-512 key management algorithms
1022
1023 ### 1.7
1024 - 250Kb limit on decompression buffer
1025 - ability to register deflate compressor with custom limits
1026
1027 ### 1.6
1028 - ability to deregister specific algorithms
1029 - configurable min/max restrictions for PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW
1030
1031 ### 1.5
1032 - security and bug fixes
1033
1034 ### 1.4
1035 - removed extra headers to be inserted by library
1036
1037 ### 1.3
1038 - security fixes: Invalid Curve Attack on NIST curves
1039
1040 ### 1.2
1041 - interface to access token headers after decoding
1042 - interface to provide extra headers for token encoding
1043 - two-phase validation support
1044
1045 ### 1.1
1046 - security and bug fixes
1047
1048 ### 1.0
1049 - initial stable version with full suite JOSE spec support