Debian Codegraph @

README.md

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