-
Notifications
You must be signed in to change notification settings - Fork 39
/
jose_example.dart
318 lines (268 loc) · 11.4 KB
/
jose_example.dart
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
import 'dart:convert';
import 'dart:io';
import 'package:crypto_keys/crypto_keys.dart';
import 'package:jose/jose.dart';
import 'package:x509/x509.dart';
void main() async {
await example1();
await example2();
await example3();
await example4();
await example5();
await example6();
await example7();
}
// decode and verify a JWS
void example1() async {
var encoded = 'eyJhbGciOiJFUzUxMiJ9.'
'UGF5bG9hZA.'
'AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZq'
'wqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8Kp'
'EHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn';
// create a JsonWebSignature from the encoded string
var jws = JsonWebSignature.fromCompactSerialization(encoded);
// extract the payload
var payload = jws.unverifiedPayload;
print('content of jws: ${payload.stringContent}');
print('protected parameters: ${payload.protectedHeader.toJson()}');
// create a JsonWebKey for verifying the signature
var jwk = JsonWebKey.fromJson({
'kty': 'EC',
'crv': 'P-521',
'x': 'AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_'
'NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk',
'y': 'ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDl'
'y79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2',
'd': 'AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPA'
'xerEzgdRhajnu0ferB0d53vM9mE15j2C'
});
var keyStore = JsonWebKeyStore()..addKey(jwk);
// verify the signature
var verified = await jws.verify(keyStore);
print('signature verified: $verified');
}
// create a JWS
void example2() async {
// create a builder
var builder = JsonWebSignatureBuilder();
// set the content
builder.stringContent = 'It is me';
// set some protected header
builder.setProtectedHeader('createdAt', DateTime.now().toIso8601String());
// add a key to sign, you can add multiple keys for different recipients
builder.addRecipient(
JsonWebKey.fromJson({
'kty': 'oct',
'k':
'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow'
}),
algorithm: 'HS256');
// build the jws
var jws = builder.build();
// output the compact serialization
print('jws compact serialization: ${jws.toCompactSerialization()}');
// output the json serialization
print('jws json serialization: ${jws.toJson()}');
}
// decode and decrypt a JWE
void example3() async {
var encoded = 'eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.'
'UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm'
'1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7Pc'
'HALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIF'
'NPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8'
'rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv'
'-B3oWh2TbqmScqXMR4gp_A.'
'AxY8DCtDaGlsbGljb3RoZQ.'
'KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.'
'9hH0vgRfYgPnAHOd8stkvw';
// create a JsonWebEncryption from the encoded string
var jwe = JsonWebEncryption.fromCompactSerialization(encoded);
// create a JsonWebKey for decrypting the signature
var jwk = JsonWebKey.fromJson(
{
'kty': 'RSA',
'n': 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl'
'UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre'
'cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_'
'7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI'
'Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU'
'7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw',
'e': 'AQAB',
'd': 'VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq'
'1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry'
'nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-Qg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Usy-WRXS-V7TbpxIhvepTfE0NNo'
},
);
var keyStore = JsonWebKeyStore()..addKey(jwk);
// decrypt the payload
var payload = await jwe.getPayload(keyStore);
print('decrypted content: ${payload.stringContent}');
}
// create a JWE
void example4() async {
// create a builder
var builder = JsonWebEncryptionBuilder();
// set the content
builder.stringContent = 'This is my bigest secret';
// set some protected header
builder.setProtectedHeader('createdAt', DateTime.now().toIso8601String());
// add a key to encrypt the Content Encryption Key
var jwk = JsonWebKey.fromJson(
{
'kty': 'RSA',
'n': 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl'
'UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre'
'cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_'
'7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI'
'Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU'
'7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw',
'e': 'AQAB',
'd': 'VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq'
'1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry'
'nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_'
'0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj'
'-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj'
'T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ',
'p': '9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68'
'ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP'
'krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM',
'q': 'uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-y'
'BhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN'
'-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0',
'dp': 'w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuv'
'ngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcra'
'Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs',
'dq': 'o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff'
'7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_'
'odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU',
'qi': 'eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC'
'tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ'
'B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo'
},
);
builder.addRecipient(jwk, algorithm: 'RSA1_5');
// set the content encryption algorithm to use
builder.encryptionAlgorithm = 'A128CBC-HS256';
// build the jws
var jwe = builder.build();
// output the compact serialization
print('jwe compact serialization: ${jwe.toCompactSerialization()}');
// output the json serialization
print('jwe json serialization: ${jwe.toJson()}');
}
// decode and verify and validate a JWT
void example5() async {
var encoded = 'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.'
'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt'
'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ.'
'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
// decode the jwt, note: this constructor can only be used for JWT inside JWS
// structures
var jwt = JsonWebToken.unverified(encoded);
// output the claims
print('claims: ${jwt.claims}');
// create key store to verify the signature
var keyStore = JsonWebKeyStore()
..addKey(JsonWebKey.fromJson({
'kty': 'oct',
'k':
'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow'
}));
var verified = await jwt.verify(keyStore);
print('verified: $verified');
// alternatively, create and verify the JsonWebToken together, this is also
// applicable for JWT inside JWE
jwt = await JsonWebToken.decodeAndVerify(encoded, keyStore);
// validate the claims
var violations = jwt.claims.validate(issuer: Uri.parse('alice'));
print('violations: $violations');
}
// create a JWT
void example6() async {
var claims = JsonWebTokenClaims.fromJson({
'exp': Duration(hours: 4).inSeconds,
'iss': 'alice',
});
// create a builder, decoding the JWT in a JWS, so using a
// JsonWebSignatureBuilder
var builder = JsonWebSignatureBuilder();
// set the content
builder.jsonContent = claims.toJson();
// add a key to sign, can only add one for JWT
builder.addRecipient(
JsonWebKey.fromJson({
'kty': 'oct',
'k':
'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow'
}),
algorithm: 'HS256');
// build the jws
var jws = builder.build();
// output the compact serialization
print('jwt compact serialization: ${jws.toCompactSerialization()}');
}
// create a JWT, sign with RS512
void example7() async {
var claims = JsonWebTokenClaims.fromJson({
'exp': Duration(hours: 4).inSeconds,
'iss': 'alice',
});
// create a builder, decoding the JWT in a JWS, so using a
// JsonWebSignatureBuilder
var builder = JsonWebSignatureBuilder();
// set the content
builder.jsonContent = claims.toJson();
// add a key to sign, can only add one for JWT
var key = _readPrivateKeyFromFile('example/jwtRS512.key');
builder.addRecipient(key, algorithm: 'RS512');
// build the jws
var jws = builder.build();
// output the compact serialization
print('jwt compact serialization: ${jws.toCompactSerialization()}');
}
JsonWebKey _readPrivateKeyFromFile(String path) {
var v = parsePem(File(path).readAsStringSync()).first;
var keyPair = (v is PrivateKeyInfo) ? v.keyPair : v as KeyPair;
var pKey = keyPair.privateKey as RsaPrivateKey;
print(pKey);
String _bytesToBase64(List<int> bytes) {
return base64Url.encode(bytes).replaceAll('=', '');
}
String _intToBase64(BigInt v) {
return _bytesToBase64(v
.toRadixString(16)
.replaceAllMapped(RegExp('[0-9a-f]{2}'), (m) => '${m.group(0)},')
.split(',')
.where((v) => v.isNotEmpty)
.map((v) => int.parse(v, radix: 16))
.toList());
}
return JsonWebKey.fromJson({
'kty': 'RSA',
'n': _intToBase64(pKey.modulus),
'd': _intToBase64(pKey.privateExponent),
'p': _intToBase64(pKey.firstPrimeFactor),
'q': _intToBase64(pKey.secondPrimeFactor),
'alg': 'RS512',
'kid': 'some_id'
});
}