blib/lib/Net/API/REST/JWT.pm untested

filter: Statementstmt 0.0% 0 / 528 Branchbran 0.0% 0 / 478 Conditioncond 0.0% 0 / 172 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 1243 CC 240 SCAR 67.3
CC
240
Cov
0%
_verify_claims
2652.0
_decode_jws
1722.0
_decode_jwe
600.0
CRAP 839.4
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## REST API Framework - ~/lib/Net/API/REST/JWT.pm
4 ## Version v0.100.4
5 ## Copyright(c) 2024 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2019/09/01
8 ## Modified 2024/09/05
9 ## All rights reserved
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package Net::API::REST::JWT;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 use common::sense;
20 use vars qw( %EXPORT_TAGS @EXPORT_OK @EXPORT $VERSION );
21 use Exporter 'import';
22 our %EXPORT_TAGS = ( all => [qw(decode_jwt encode_jwt)] );
23 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
24 our @EXPORT = qw();
25  
26 # use Carp;
27 use Crypt::Misc qw(decode_b64u encode_b64u);
28 # use JSON::MaybeXS qw(decode_json encode_json);
29 # JSON::XS does not play well with ModPerl, so luckily we can use the Pure Perl version
30 use JSON::PP qw( decode_json encode_json );
31 use Crypt::PK::RSA;
32 use Crypt::PK::ECC;
33 use Crypt::PRNG qw(random_bytes);
34 use Crypt::KeyWrap ':all';
35 use Crypt::AuthEnc::GCM qw(gcm_encrypt_authenticate gcm_decrypt_verify);
36 use Crypt::Mac::HMAC qw(hmac);
37 use Compress::Raw::Zlib;
38 use Scalar::Util qw(looks_like_number);
39 # Crypt::JWT version 0.024
40 our $VERSION = 'v0.100.4';
41 };
42  
43 use strict;
44 use warnings;
45  
46 # JWS: https://tools.ietf.org/html/rfc7515
47 # JWE: https://tools.ietf.org/html/rfc7516
48 # JWK: https://tools.ietf.org/html/rfc7517
49 # JWA: https://tools.ietf.org/html/rfc7518
50 # JWT: https://tools.ietf.org/html/rfc7519
51  
52 sub decode_jwt
53 {
54 my %args = @_;
55 my( $header, $payload );
56 print( STDERR __PACKAGE__ . "::decode_jwt() [", __LINE__, "]: Token to decode is: $args{token}\n" ) if( $args{debug} );
57  
58 if( !$args{token} )
59 {
60 die( "JWT: missing token" );
61 }
62 elsif( $args{token} =~ /^([a-zA-Z0-9_-]+)=*\.([a-zA-Z0-9_-]*)=*\.([a-zA-Z0-9_-]+)=*\.([a-zA-Z0-9_-]+)=*\.([a-zA-Z0-9_-]+)=*$/ )
63 {
64 # JWE token (5 segments)
65 print( STDERR __PACKAGE__ . "::decode_jwt() [", __LINE__, "]: Token is an encrypted token\n" ) if( $args{debug} );
66 ( $header, $payload ) = _decode_jwe( $1, $2, $3, $4, $5, undef(), {}, {}, %args );
67 }
68 elsif( $args{token} =~ /^([a-zA-Z0-9_-]+)=*\.([a-zA-Z0-9_-]+)=*\.([a-zA-Z0-9_-]*)=*$/ )
69 {
70 # JWS token (3 segments)
71 print( STDERR __PACKAGE__ . "::decode_jwt() [", __LINE__, "]: Token is a 3-segment token\n" ) if( $args{debug} );
72 ( $header, $payload ) = _decode_jws( $1, $2, $3, {}, %args );
73 }
74 elsif( $args{token} =~ /^\s*\{.*?\}\s*$/s )
75 {
76 print( STDERR __PACKAGE__ . "::decode_jwt() [", __LINE__, "]: Token provided is wrapped in json, decoding first.\n" ) if( $args{debug} );
77 my $hash = decode_json( $args{token} );
78 if( $hash->{payload} && $hash->{protected} )
79 {
80 # Flattened JWS JSON Serialization
81 ( $header, $payload ) = _decode_jws( $hash->{protected}, $hash->{payload}, $hash->{signature}, $hash->{header}, %args );
82 }
83 elsif( $hash->{ciphertext} && $hash->{protected} )
84 {
85 # Flattened JWE JSON Serialization
86 ( $header, $payload ) = _decode_jwe( $hash->{protected}, $hash->{encrypted_key}, $hash->{iv}, $hash->{ciphertext}, $hash->{tag}, $hash->{aad}, $hash->{header}, $hash->{unprotected}, %args );
87 }
88 else
89 {
90 die( "JWT: unsupported JWS/JWT JSON Serialization" );
91 }
92 }
93 else
94 {
95 print( STDERR __PACKAGE__ . "::decode_jwt() [", __LINE__, "]: Unknown token, dying...\n" ) if( $args{debug} );
96 die( "JWT: invalid token format" );
97 }
98 print( STDERR __PACKAGE__ . "::decode_jwt() [", __LINE__, "]: Returning header and payload\n" ) if( $args{debug} );
99 return( $header, $payload ) if( $args{decode_header} );
100 return( $payload );
101 }
102  
103 sub encode_jwt
104 {
105 my %args = @_;
106  
107 my $ser = $args{serialization} || 'compact';
108 if( $args{alg} =~ /^(none|((HS|RS|PS|ES)(512|384|256)))$/ )
109 {
110 ###JWS
111 my( $b64u_header, $b64u_payload, $b64u_signature ) = _encode_jws( %args );
112 # https://tools.ietf.org/html/rfc7515#section-7.1
113 if( $ser eq 'compact' )
114 {
115 die( "JWT: cannot use 'unprotected_headers' with compact serialization" ) if( defined( $args{unprotected_headers} ) );
116 return( "$b64u_header.$b64u_payload.$b64u_signature" );
117 }
118 # https://tools.ietf.org/html/rfc7515#section-7.2.2
119 elsif( $ser eq 'flattened' )
120 {
121 my $token =
122 {
123 protected => $b64u_header,
124 payload => $b64u_payload,
125 signature => $b64u_signature
126 };
127 $token->{header} = \%{$args{unprotected_headers}} if( ref( $args{unprotected_headers} ) eq 'HASH' );
128 my $j = JSON->new->allow_nonref->allow_blessed->convert_blessed;
129 # return encode_json($token);
130 return( $j->encode( $token ) );
131 }
132 else
133 {
134 die( "JWT: unsupported JWS serialization '$ser'" );
135 }
136 }
137 else
138 {
139 ### JWE
140 my( $b64u_header, $b64u_ecek, $b64u_iv, $b64u_ct, $b64u_tag, $b64u_aad ) = _encode_jwe( %args );
141 # https://tools.ietf.org/html/rfc7516#section-7.1
142 if( $ser eq 'compact' )
143 {
144 die( "JWT: cannot use 'aad' with compact serialization" ) if( defined( $args{aad} ) );
145 die( "JWT: cannot use 'unprotected_headers' with compact serialization" ) if( defined( $args{unprotected_headers} ) );
146 die( "JWT: cannot use 'shared_unprotected_headers' with compact serialization" ) if( defined( $args{shared_unprotected_headers} ) );
147 return( "$b64u_header.$b64u_ecek.$b64u_iv.$b64u_ct.$b64u_tag" );
148 }
149 # https://tools.ietf.org/html/rfc7516#section-7.2.2
150 elsif( $ser eq 'flattened' )
151 {
152 my $token = {
153 protected => $b64u_header,
154 encrypted_key => $b64u_ecek,
155 iv => $b64u_iv,
156 ciphertext => $b64u_ct,
157 tag => $b64u_tag,
158 };
159 # header: JWE Per-Recipient Unprotected Header when the JWE Per-Recipient Unprotected Header
160 $token->{header} = \%{$args{unprotected_headers}} if( ref( $args{unprotected_headers} ) eq 'HASH' );
161 # unprotected: JWE Shared Unprotected Header
162 $token->{unprotected} = \%{$args{shared_unprotected_headers}} if( ref( $args{shared_unprotected_headers} ) eq 'HASH' );
163 # aad: Additional Authenticated Data (AAD)
164 $token->{aad} = $b64u_aad if( defined( $b64u_aad ) );
165 # return( encode_json( $token ) );
166 my $j = JSON->new->allow_nonref->allow_blessed->convert_blessed;
167 return( $j->encode( $token ) );
168 }
169 else
170 {
171 die( "JWT: unsupported JWE serialization '$ser'" );
172 }
173 }
174 }
175  
176 sub _prepare_rsa_key
177 {
178 my( $key ) = @_;
179 die( "JWT: undefined RSA key" ) unless( defined( $key ) );
180 die( "JWT: invalid RSA key (cannot be scalar)" ) unless( ref( $key ) );
181 # we need Crypt::PK::RSA object
182 return( $key ) if( ref( $key ) eq 'Crypt::PK::RSA' );
183 return( Crypt::PK::RSA->new( $key ) ) if( ref( $key ) eq 'HASH' || ref( $key ) eq 'SCALAR' );
184 return( Crypt::PK::RSA->new( @$key ) ) if( ref( $key ) eq 'ARRAY' );
185 # handle also: Crypt::OpenSSL::RSA, Crypt::X509, Crypt::OpenSSL::X509
186 my $str;
187 if( ref( $key ) eq 'Crypt::OpenSSL::RSA' )
188 {
189 # https://metacpan.org/pod/Crypt::OpenSSL::RSA
190 $str = $key->is_private ? $key->get_private_key_string : $key->get_public_key_string;
191 }
192 elsif( ref( $key ) =~ /^Crypt::(X509|OpenSSL::X509)$/ )
193 {
194 # https://metacpan.org/pod/Crypt::X509
195 # https://metacpan.org/pod/Crypt::OpenSSL::X509
196 $str = $key->pubkey;
197 }
198 return( Crypt::PK::RSA->new( \$str ) ) if( defined( $str ) && !ref( $str ) );
199 die( "JWT: invalid RSA key" );
200 }
201  
202 sub _prepare_ecc_key
203 {
204 my( $key ) = @_;
205 die( "JWT: undefined ECC key" ) unless( defined( $key ) );
206 die( "JWT: invalid ECC key (cannot be scalar)" ) unless( ref( $key ) );
207 # we need Crypt::PK::ECC object
208 return( $key ) if( ref( $key ) eq 'Crypt::PK::ECC' );
209 return( Crypt::PK::ECC->new( $key ) ) if( ref( $key ) eq 'HASH' || ref( $key ) eq 'SCALAR' );
210 return( Crypt::PK::ECC->new( @$key ) ) if( ref( $key ) eq 'ARRAY' );
211 die( "JWT: invalid ECC key" );
212 }
213  
214 sub _prepare_oct_key
215 {
216 my( $key ) = @_;
217 die( "JWT: undefined oct key" ) unless( defined( $key ) );
218 if( ref( $key ) eq 'HASH' && $key->{k} && $key->{kty} && $key->{kty} eq 'oct' )
219 {
220 return( decode_b64u( $key->{k} ) );
221 }
222 elsif( !ref( $key ) )
223 {
224 return( $key );
225 }
226 die( "JWT: invalid oct key" );
227 }
228  
229 sub _kid_lookup
230 {
231 my( $kid, $kid_keys, $alg ) = @_;
232 return( undef() ) if( !defined( $kid ) || !defined( $alg ) );
233 $kid_keys = eval{ decode_json( $kid_keys ) } if( $kid_keys && !ref( $kid_keys ) );
234 die( "JWT: kid_keys must be a HASHREF or a valid JSON/HASH" ) if( ref( $kid_keys ) ne 'HASH' );
235 my $found;
236 if( exists( $kid_keys->{keys} ) && ref( $kid_keys->{keys} ) eq 'ARRAY' )
237 {
238 #FORMAT: { keys => [ {kid=>'A', kty=>?, ...}, {kid=>'B', kty=>?, ...} ] }
239 for( @{$kid_keys->{keys}} )
240 {
241 if( $_->{kid} && $_->{kty} && $_->{kid} eq $kid )
242 {
243 $found = $_;
244 last;
245 }
246 }
247 }
248 else
249 {
250 #FORMAT: { hexadec1 => "----BEGIN CERTIFICATE-----...", hexadec2 => "----BEGIN CERTIFICATE-----..." }
251 #e.g. https://www.googleapis.com/oauth2/v1/certs
252 return( \$kid_keys->{$kid} ) if( $kid_keys->{$kid} && !ref( $kid_keys->{$kid} ) );
253 }
254 return( undef() ) if( !$found );
255 return( $found ) if( $found->{kty} eq 'oct' && $alg =~ /^(HS|dir|PBES2-HS|A)/ );
256 return( $found ) if( $found->{kty} eq 'EC' && $alg =~ /^(ES|EC)/ );
257 return( $found ) if( $found->{kty} eq 'RSA' && $alg =~ /^RS/ );
258 die( "JWT: key type '$found->{kty}' cannot be used with alg '$alg'" );
259 }
260  
261 sub _b64u_to_hash
262 {
263 my $b64url = shift;
264 return( undef() ) unless( $b64url );
265 my $json = decode_b64u( $b64url );
266 return( undef() ) unless( $json );
267 my $hash = eval{ decode_json( $json ) };
268 return( undef() ) unless( ref( $hash ) eq 'HASH' );
269 return( $hash );
270 }
271  
272 sub _add_claims
273 {
274 my( $payload, %args ) = @_;
275 #### claims (defined for JWS only)
276 # "exp" Expiration Time
277 # "nbf" Not Before
278 # "iat" Issued At
279 # "iss" Issuer
280 # "sub" Subject
281 # "aud" Audience
282 # "jti" JWT ID
283 my $now = time();
284 $payload->{iat} = $now if( $args{auto_iat} );
285 $payload->{exp} = $now + $args{relative_exp} if( defined( $args{relative_exp} ) );
286 $payload->{nbf} = $now + $args{relative_nbf} if( defined( $args{relative_nbf} ) );
287 }
288  
289 sub _verify_claims
290 {
291 my( $payload, %args ) = @_;
292  
293 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Ignoring claim verification, nothing to do here, returning\n" ) if( $args{debug} && $args{ignore_claims} );
294 return if( $args{ignore_claims} );
295  
296 my $leeway = $args{leeway} || 0;
297 my $now = time();
298  
299 ### exp
300 if( defined( $payload->{exp} ) )
301 {
302 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking expiration $payload->{exp}\n" ) if( $args{debug} );
303 if( !defined( $args{verify_exp} ) || $args{verify_exp} == 1 )
304 {
305 die( "JWT: exp claim check failed ($payload->{exp}/$leeway vs. $now)" ) if( $payload->{exp} + $leeway <= $now );
306 }
307 }
308 elsif( $args{verify_exp} && $args{verify_exp} == 1 )
309 {
310 die( "JWT: exp claim required but missing" );
311 }
312  
313 ### nbf
314 if( defined( $payload->{nbf} ) )
315 {
316 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking mbf $payload->{nbf}\n" ) if( $args{debug} );
317 if( !defined( $args{verify_nbf} ) || $args{verify_nbf} == 1 )
318 {
319 die( "JWT: nbf claim check failed ($payload->{nbf}/$leeway vs. $now)" ) if( $payload->{nbf} - $leeway > $now );
320 }
321 }
322 elsif( $args{verify_nbf} && $args{verify_nbf} == 1 )
323 {
324 die( "JWT: nbf claim required but missing" );
325 }
326  
327 ### iat
328 #default (non existing verify_iat) == no iat check
329 if( exists( $args{verify_iat} ) )
330 {
331 if( defined( $payload->{iat} ) )
332 {
333 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking iat $payload->{iat}\n" ) if( $args{debug} );
334 if( !defined( $args{verify_iat} ) || $args{verify_iat} == 1 )
335 {
336 die( "JWT: iat claim check failed ($payload->{iat}/$leeway vs. $now)" ) if( $payload->{iat} - $leeway > $now );
337 }
338 }
339 elsif( $args{verify_iat} && $args{verify_iat} == 1 )
340 {
341 die( "JWT: iat claim required but missing" );
342 }
343 }
344  
345 ### iss
346 if( exists( $args{verify_iss} ) )
347 {
348 if( exists( $payload->{iss} ) )
349 {
350 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking issuer $payload->{iss}\n" ) if( $args{debug} );
351 if( ref( $args{verify_iss} ) eq 'Regexp' )
352 {
353 die( "JWT: iss claim re check failed" ) unless( $payload->{iss} =~ $args{verify_iss} );
354 }
355 elsif( ref( $args{verify_iss} ) eq 'CODE' )
356 {
357 die( "JWT: iss claim check failed" ) unless( $args{verify_iss}->( $payload->{iss} ) );
358 }
359 else
360 {
361 die( "JWT: verify_iss must be Regexp or CODE" );
362 }
363 }
364 elsif( $args{verify_iss} )
365 {
366 die( "JWT: iss claim required but missing" );
367 }
368 }
369  
370 ### sub
371 if( exists( $args{verify_sub} ) )
372 {
373 if( exists( $payload->{sub} ) )
374 {
375 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking sub $payload->{sub}\n" ) if( $args{debug} );
376 if( ref( $args{verify_sub} ) eq 'Regexp' )
377 {
378 die( "JWT: sub claim re check failed" ) unless( $payload->{sub} =~ $args{verify_sub} );
379 }
380 elsif( ref( $args{verify_sub} ) eq 'CODE' )
381 {
382 die( "JWT: sub claim check failed" ) unless( $args{verify_sub}->( $payload->{sub} ) );
383 }
384 else
385 {
386 die( "JWT: verify_sub must be Regexp or CODE" );
387 }
388 }
389 elsif( $args{verify_sub} )
390 {
391 die( "JWT: sub claim required but missing" );
392 }
393 }
394  
395 ### aud
396 if( exists( $args{verify_aud} ) )
397 {
398 if( exists( $payload->{aud} ) )
399 {
400 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking aud $payload->{aud}\n" ) if( $args{debug} );
401 if( ref( $args{verify_aud} ) eq 'Regexp' )
402 {
403 die( "JWT: aud claim re check failed" ) unless( $payload->{aud} =~ $args{verify_aud} );
404 }
405 elsif( ref( $args{verify_aud} ) eq 'CODE' )
406 {
407 die( "JWT: aud claim check failed" ) unless( $args{verify_aud}->( $payload->{aud} ) );
408 }
409 else
410 {
411 die( "JWT: verify_aud must be Regexp or CODE" );
412 }
413 }
414 elsif( $args{verify_aud} )
415 {
416 die( "JWT: aud claim required but missing" );
417 }
418 }
419  
420 ### jti
421 if( exists( $args{verify_jti} ) )
422 {
423 if( exists( $payload->{jti} ) )
424 {
425 print( STDERR __PACKAGE__ . "::_verify_claims() [", __LINE__, "]: Checking jti $payload->{jti}\n" ) if( $args{debug} );
426 if( ref( $args{verify_jti} ) eq 'Regexp' )
427 {
428 die( "JWT: jti claim re check failed" ) unless( $payload->{jti} =~ $args{verify_jti} );
429 }
430 elsif( ref( $args{verify_jti} ) eq 'CODE' )
431 {
432 die( "JWT: jti claim check failed" ) unless( $args{verify_jti}->( $payload->{jti} ) );
433 }
434 else
435 {
436 die( "JWT: verify_jti must be Regexp or CODE" );
437 }
438 }
439 elsif( $args{verify_jti} )
440 {
441 die( "JWT: jti claim required but missing" );
442 }
443 }
444 }
445  
446 sub _payload_zip
447 {
448 my( $payload, $header, $z ) = @_;
449 my @zip = ref( $z ) eq 'ARRAY' ? @$z : ( $z );
450 if( $zip[0] eq 'deflate' )
451 {
452 my $level = defined( $zip[1] ) ? $zip[1] : 6;
453 $header->{zip} = "DEF";
454 my $d = Compress::Raw::Zlib::Deflate->new(
455 -Bufsize => 1024,
456 -WindowBits => -&MAX_WBITS(),
457 -AppendOutput => 1,
458 -Level => $level
459 );
460 my $output = '';
461 $d->deflate( $payload, $output ) == Z_OK or die( "JWT: deflate failed" );
462 $d->flush( $output ) == Z_OK or die( "JWT: deflate/flush failed" );
463 die( "JWT: deflate/output failed" ) unless( $output );
464 $payload = $output;
465 }
466 else
467 {
468 die( "JWT: unknown zip method '$zip[0]'" );
469 }
470 return( $payload );
471 }
472  
473 sub _payload_unzip
474 {
475 my( $payload, $z ) = @_;
476 if( $z eq "DEF" )
477 {
478 my $d = Compress::Raw::Zlib::Inflate->new(
479 -Bufsize => 1024,
480 -WindowBits => -&MAX_WBITS()
481 );
482 my $output = '';
483 $d->inflate( $payload, $output );
484 die( "JWT: inflate failed" ) unless( $output );
485 $payload = $output;
486 }
487 else
488 {
489 die( "JWT: unknown zip method '$z'" );
490 }
491 return( $payload );
492 }
493  
494 sub _payload_enc
495 {
496 my( $payload ) = @_;
497 if( ref( $payload ) =~ /^(HASH|ARRAY)$/ )
498 {
499 # $payload = encode_json( $payload );
500 my $j = JSON->new->allow_nonref->allow_blessed->convert_blessed;
501 # try-catch
502 local $@;
503 $payload = eval
504 {
505 $j->encode( $payload );
506 };
507 die( "Error JSON encoding payload: $@" ) if( $@ );
508 }
509 else
510 {
511 utf8::downgrade( $payload, 1 ) or die( "JWT: payload cannot contain wide character" );
512 }
513 return( $payload );
514 }
515  
516 sub _payload_dec
517 {
518 my( $payload, $decode_payload ) = @_;
519 return( $payload ) if( defined( $decode_payload ) && $decode_payload == 0 );
520 my $de = $payload;
521 $de = eval{ decode_json( $de ) };
522 if( $decode_payload )
523 {
524 die( "JWT: payload not a valid JSON" ) unless( $de );
525 return( $de );
526 }
527 else
528 {
529 return( defined( $de ) ? $de : $payload );
530 }
531 }
532  
533 sub _encrypt_jwe_cek
534 {
535 my( $key, $hdr ) = @_;
536 my $alg = $hdr->{alg};
537 my $enc = $hdr->{enc};
538  
539 if( $alg eq 'dir' )
540 {
541 return( ( _prepare_oct_key( $key ), '' ) );
542 }
543  
544 my $cek;
545 my $ecek;
546 if( $enc =~ /^A(128|192|256)GCM/ )
547 {
548 $cek = random_bytes( $1 / 8 );
549 }
550 elsif( $enc =~ /^A(128|192|256)CBC/ )
551 {
552 $cek = random_bytes( 2 * $1 / 8 );
553 }
554  
555 if( $alg =~ /^A(128|192|256)KW$/ )
556 {
557 $ecek = aes_key_wrap( _prepare_oct_key( $key ), $cek );
558 return( ( $cek, $ecek ) );
559 }
560 elsif( $alg =~ /^A(128|192|256)GCMKW$/ )
561 {
562 my( $t, $i );
563 ( $ecek, $t, $i ) = gcm_key_wrap( _prepare_oct_key( $key ), $cek );
564 $hdr->{tag} = encode_b64u( $t );
565 $hdr->{iv} = encode_b64u( $i );
566 return( ( $cek, $ecek ) );
567 }
568 elsif( $alg =~ /^PBES2-HS(512|384|256)\+A(128|192|256)KW$/ )
569 {
570 my $len = looks_like_number( $hdr->{p2s} ) && $hdr->{p2s} >= 8 && $hdr->{p2s} <= 9999 ? $hdr->{p2s} : 16;
571 my $salt = random_bytes( $len );
572 my $iter = looks_like_number( $hdr->{p2c} ) ? $hdr->{p2c} : 5000;
573 $ecek = pbes2_key_wrap( _prepare_oct_key( $key ), $cek, $alg, $salt, $iter );
574 $hdr->{p2s} = encode_b64u( $salt );
575 $hdr->{p2c} = $iter;
576 return( ( $cek, $ecek ) );
577 }
578 elsif( $alg =~ /^RSA(-OAEP|-OAEP-256|1_5)$/ )
579 {
580 $key = _prepare_rsa_key( $key );
581 $ecek = rsa_key_wrap( $key, $cek, $alg );
582 return( ( $cek, $ecek ) );
583 }
584 elsif( $alg =~ /^ECDH-ES\+A(128|192|256)KW$/ )
585 {
586 $key = _prepare_ecc_key( $key );
587 ( $ecek, $hdr->{epk} ) = ecdhaes_key_wrap( $key, $cek, $alg, $hdr->{apu}, $hdr->{apv} );
588 return( ( $cek, $ecek ) );
589 }
590 elsif( $alg eq 'ECDH-ES' )
591 {
592 $key = _prepare_ecc_key( $key );
593 ( $cek, $hdr->{epk} ) = ecdh_key_wrap( $key, $enc, $hdr->{apu}, $hdr->{apv} );
594 return( ( $cek, '' ) );
595 }
596 die( "JWE: unknown alg '$alg'" );
597 }
598  
599 sub _decrypt_jwe_cek
600 {
601 my( $ecek, $key, $hdr ) = @_;
602 my $alg = $hdr->{alg};
603 my $enc = $hdr->{enc};
604  
605 if( $alg eq 'dir' )
606 {
607 return( _prepare_oct_key( $key ) );
608 }
609 elsif( $alg =~ /^A(128|192|256)KW$/ )
610 {
611 return( aes_key_unwrap( _prepare_oct_key( $key ), $ecek ) );
612 }
613 elsif( $alg =~ /^A(128|192|256)GCMKW$/ )
614 {
615 return( gcm_key_unwrap( _prepare_oct_key( $key ), $ecek, decode_b64u( $hdr->{tag} ), decode_b64u( $hdr->{iv} ) ) );
616 }
617 elsif( $alg =~ /^PBES2-HS(512|384|256)\+A(128|192|256)KW$/ )
618 {
619 return( pbes2_key_unwrap( _prepare_oct_key( $key ), $ecek, $alg, decode_b64u( $hdr->{p2s} ), $hdr->{p2c} ) );
620 }
621 elsif( $alg =~ /^RSA(-OAEP|-OAEP-256|1_5)$/ )
622 {
623 $key = _prepare_rsa_key( $key );
624 return( rsa_key_unwrap( $key, $ecek, $alg ) );
625 }
626 elsif( $alg =~ /^ECDH-ES\+A(128|192|256)KW$/ )
627 {
628 $key = _prepare_ecc_key( $key );
629 return( ecdhaes_key_unwrap( $key, $ecek, $alg, $hdr->{epk}, $hdr->{apu}, $hdr->{apv} ) );
630 }
631 elsif( $alg eq 'ECDH-ES' )
632 {
633 $key = _prepare_ecc_key( $key );
634 return( ecdh_key_unwrap( $key, $enc, $hdr->{epk}, $hdr->{apu}, $hdr->{apv} ) );
635 }
636 die( "JWE: unknown alg '$alg'" );
637 }
638  
639 sub _encrypt_jwe_payload
640 {
641 my( $cek, $enc, $b64u_header, $b64u_aad, $payload ) = @_;
642 my $aad = defined( $b64u_aad ) ? "$b64u_header.$b64u_aad" : $b64u_header;
643 if( $enc =~ /^A(128|192|256)GCM$/ )
644 {
645 # https://tools.ietf.org/html/rfc7518#section-5.3
646 my $len1 = $1/8;
647 my $len2 = length($cek);
648 die( "JWE: wrong AES key length ($len1 vs. $len2) for $enc" ) unless( $len1 == $len2 );
649 # for AESGCM always 12 (96 bits)
650 my $iv = random_bytes( 12 );
651 my( $ct, $tag ) = gcm_encrypt_authenticate( 'AES', $cek, $iv, $aad, $payload );
652 return( ( $ct, $iv, $tag ) );
653 }
654 elsif( $enc =~ /^A(128|192|256)CBC-HS(256|384|512)$/ )
655 {
656 # https://tools.ietf.org/html/rfc7518#section-5.2
657 my( $size, $hash ) = ( $1 / 8, "SHA$2" );
658 my $key_len = length( $cek ) / 2;
659 my $mac_key = substr( $cek, 0, $key_len );
660 my $aes_key = substr( $cek, $key_len, $key_len );
661 die( "JWE: wrong AES key length ($key_len vs. $size)" ) unless( $key_len == $size );
662 # for AES always 16
663 my $iv = random_bytes( 16 );
664 my $m = Crypt::Mode::CBC->new( 'AES' );
665 my $ct = $m->encrypt( $payload, $aes_key, $iv );
666 my $aad_len = length( $aad );
667 my $mac_input = $aad . $iv . $ct . pack( 'N2', ( $aad_len / 2147483647 ) * 8, ( $aad_len % 2147483647 ) * 8 );
668 my $mac = hmac( $hash, $mac_key, $mac_input );
669 my $sig_len = length( $mac ) / 2;
670 my $sig = substr( $mac, 0, $sig_len );
671 return( ( $ct, $iv, $sig ) );
672 }
673 die( "JWE: unsupported enc '$enc'" );
674 }
675  
676 sub _decrypt_jwe_payload
677 {
678 my( $cek, $enc, $aad, $ct, $iv, $tag ) = @_;
679 if( $enc =~ /^A(128|192|256)GCM$/ )
680 {
681 # https://tools.ietf.org/html/rfc7518#section-5.3
682 my $len1 = $1/8;
683 my $len2 = length( $cek );
684 die( "JWE: wrong AES key length ($len1 vs. $len2) for $enc" ) unless( $len1 == $len2 );
685 return( gcm_decrypt_verify( 'AES', $cek, $iv, $aad, $ct, $tag ) );
686 }
687 elsif( $enc =~ /^A(128|192|256)CBC-HS(256|384|512)$/ )
688 {
689 # https://tools.ietf.org/html/rfc7518#section-5.2
690 my( $size, $hash ) = ( $1 / 8, "SHA$2" );
691 my $key_len = length( $cek ) / 2;
692 my $mac_key = substr( $cek, 0, $key_len );
693 my $aes_key = substr( $cek, $key_len, $key_len );
694 die( "JWE: wrong AES key length ($key_len vs. $size)" ) unless( $key_len == $size );
695 # AAD == original encoded header
696 my $aad_len = length( $aad );
697 my $mac_input = $aad . $iv . $ct . pack( 'N2', ( $aad_len / 2147483647 ) * 8, ( $aad_len % 2147483647 ) * 8 );
698 my $mac = hmac( $hash, $mac_key, $mac_input );
699 my $sig_len = length( $mac ) / 2;
700 my $sig = substr( $mac, 0, $sig_len );
701 die( "JWE: tag mismatch" ) unless( $sig eq $tag );
702 my $m = Crypt::Mode::CBC->new( 'AES' );
703 my $pt = $m->decrypt( $ct, $aes_key, $iv );
704 return( $pt );
705 }
706 die( "JWE: unsupported enc '$enc'" );
707 }
708  
709 sub _encode_jwe
710 {
711 my %args = @_;
712 my $payload = $args{payload};
713 my $alg = $args{alg};
714 my $enc = $args{enc};
715 my $header = $args{extra_headers} ? \%{$args{extra_headers}} : {};
716 # add claims to payload
717 _add_claims( $payload, %args ) if( ref( $payload ) eq 'HASH' );
718 # serialize payload
719 $payload = _payload_enc( $payload );
720 # compress payload
721 # may set some header items
722 $payload = _payload_zip( $payload, $header, $args{zip} ) if( $args{zip} );
723 # prepare header
724 $header->{alg} = $alg;
725 $header->{enc} = $enc;
726 # key
727 die( "JWE: missing 'key'" ) if( !$args{key} );
728 my $key = defined( $args{keypass} ) ? [ $args{key}, $args{keypass} ] : $args{key};
729 # prepare cek
730 # adds some header items
731 my( $cek, $ecek ) = _encrypt_jwe_cek( $key, $header );
732 # encode header
733 my $j = JSON->new->allow_nonref->allow_blessed->convert_blessed;
734 # my $json_header = encode_json( $header );
735 my $json_header = $j->encode( $header );
736 my $b64u_header = encode_b64u( $json_header );
737 my $b64u_aad = defined( $args{aad} ) ? encode_b64u( $args{aad} ) : undef;
738 # encrypt payload
739 my( $ct, $iv, $tag ) = _encrypt_jwe_payload( $cek, $enc, $b64u_header, $b64u_aad, $payload );
740 # return token parts
741 return( $b64u_header,
742 encode_b64u( $ecek ),
743 encode_b64u( $iv ),
744 encode_b64u( $ct ),
745 encode_b64u( $tag ),
746 $b64u_aad );
747 }
748  
749 sub _decode_jwe
750 {
751 my( $b64u_header, $b64u_ecek, $b64u_iv, $b64u_ct, $b64u_tag, $b64u_aad, $unprotected, $shared_unprotected, %args ) = @_;
752 my $header = _b64u_to_hash( $b64u_header );
753 my $ecek = decode_b64u( $b64u_ecek );
754 my $ct = decode_b64u( $b64u_ct );
755 my $iv = decode_b64u( $b64u_iv );
756 my $tag = decode_b64u( $b64u_tag );
757 die( "JWE: invalid header part" ) if( $b64u_header && !$header );
758 die( "JWE: invalid ecek part" ) if( $b64u_ecek && !$ecek );
759 die( "JWE: invalid ct part" ) if( $b64u_ct && !$ct );
760 die( "JWE: invalid iv part" ) if( $b64u_iv && !$iv );
761 die( "JWE: invalid tag part" ) if( $b64u_tag && !$tag );
762  
763 my $key;
764 if( exists( $args{key} ) )
765 {
766 $key = defined( $args{keypass} ) ? [ $args{key}, $args{keypass} ] : $args{key};
767 }
768 elsif( exists( $args{kid_keys} ) )
769 {
770 # BEWARE: stricter approach since 0.023
771 # when 'kid_keys' specified it croaks if header doesn't contain 'kid' value or if 'kid' wasn't found in 'kid_keys'
772 my $k = _kid_lookup( $header->{kid}, $args{kid_keys}, $header->{alg} );
773 die( "JWE: kid_keys lookup failed" ) if( !defined( $k ) );
774 $key = $k;
775 }
776 die( "JWE: missing key" ) if( !defined( $key ) );
777  
778 my $aa = $args{accepted_alg};
779 if( ref( $aa ) eq 'Regexp' )
780 {
781 die( "JWE: alg '$header->{alg}' does not match accepted_alg" ) if( $header->{alg} !~ $aa );
782 }
783 elsif( $aa && ( ref( $aa ) eq 'ARRAY' || !ref( $aa ) ) )
784 {
785 my %acca = ref( $aa ) ? map{ $_ => 1 } @$aa : ( $aa => 1 );
786 die( "JWE: alg '$header->{alg}' not in accepted_alg" ) if( !$acca{$header->{alg}} );
787 }
788  
789 my $ae = $args{accepted_enc};
790 if( ref( $ae ) eq 'Regexp' )
791 {
792 die( "JWE: enc '$header->{enc}' does not match accepted_enc" ) if( $header->{enc} !~ $ae );
793 }
794 elsif( $ae && ( ref( $ae ) eq 'ARRAY' || !ref( $ae ) ) )
795 {
796 my %acce = ref( $ae ) ? map{ $_ => 1 } @$ae : ( $ae => 1 );
797 die( "JWE: enc '$header->{enc}' not in accepted_enc" ) if( !$acce{$header->{enc}} );
798 }
799  
800 # merge headers
801 $header = { %$shared_unprotected, %$unprotected, %$header };
802 my $cek = _decrypt_jwe_cek( $ecek, $key, $header );
803 my $aad = defined( $b64u_aad ) ? "$b64u_header.$b64u_aad" : $b64u_header;
804 my $payload = _decrypt_jwe_payload( $cek, $header->{enc}, $aad, $ct, $iv, $tag );
805 $payload = _payload_unzip( $payload, $header->{zip} ) if( $header->{zip} );
806 $payload = _payload_dec( $payload, $args{decode_payload} );
807 # croaks on error
808 _verify_claims( $payload, %args ) if( ref( $payload ) eq 'HASH' );
809 return( ( $header, $payload ) );
810 }
811  
812 sub _sign_jws
813 {
814 my( $b64u_header, $b64u_payload, $alg, $key ) = @_;
815 # no integrity
816 return( '' ) if( $alg eq 'none' );
817 my $sig;
818 my $data = "$b64u_header.$b64u_payload";
819 # HMAC integrity
820 if( $alg =~ /^HS(256|384|512)$/ )
821 {
822 $key = _prepare_oct_key( $key );
823 $sig = hmac( "SHA$1", $key, $data );
824 }
825 # RSA+PKCS1-V1_5 signatures
826 elsif( $alg =~ /^RS(256|384|512)/ )
827 {
828 my $pk = _prepare_rsa_key( $key );
829 $sig = $pk->sign_message( $data, "SHA$1", 'v1.5' );
830 }
831 # RSA+PSS signatures
832 elsif( $alg =~ /^PS(256|384|512)/ )
833 {
834 my $hash = "SHA$1";
835 my $hashlen = $1/8;
836 my $pk = _prepare_rsa_key( $key );
837 $sig = $pk->sign_message( $data, $hash, 'pss', $hashlen );
838 }
839 # ECDSA signatures
840 elsif( $alg =~ /^ES(256|384|512)/ )
841 {
842 my $pk = _prepare_ecc_key( $key );
843 $sig = $pk->sign_message_rfc7518( $data, "SHA$1" );
844 }
845 return( encode_b64u( $sig ) );
846 }
847  
848 sub _verify_jws
849 {
850 my( $b64u_header, $b64u_payload, $b64u_sig, $alg, $key ) = @_;
851 my $sig = decode_b64u( $b64u_sig );
852 die( "JWS: invalid sig part" ) if( $b64u_sig && !$sig );
853 my $data = "$b64u_header.$b64u_payload";
854  
855 # no integrity
856 if( $alg eq 'none' )
857 {
858 return( 1 );
859 }
860 # HMAC integrity
861 elsif( $alg =~ /^HS(256|384|512)$/ )
862 {
863 $key = _prepare_oct_key( $key );
864 return( 1 ) if( $sig eq hmac( "SHA$1", $key, $data ) );
865 }
866 # RSA+PKCS1-V1_5 signatures
867 elsif( $alg =~ /^RS(256|384|512)/ )
868 {
869 my $hash = "SHA$1";
870 my $pk = _prepare_rsa_key( $key );
871 return( 1 ) if( $pk->verify_message( $sig, $data, $hash, 'v1.5' ) );
872 }
873 # RSA+PSS signatures
874 elsif( $alg =~ /^PS(256|384|512)/ )
875 {
876 my $hash = "SHA$1";
877 my $hashlen = $1/8;
878 my $pk = _prepare_rsa_key( $key );
879 return( 1 ) if( $pk->verify_message( $sig, $data, $hash, 'pss', $hashlen ) );
880 }
881 # ECDSA signatures
882 elsif( $alg =~ /^ES(256|384|512)/ )
883 {
884 my $hash = "SHA$1";
885 my $pk = _prepare_ecc_key( $key );
886 return( 1 ) if( $pk->verify_message_rfc7518( $sig, $data, $hash ) );
887 }
888 return( 0 );
889 }
890  
891 sub _encode_jws
892 {
893 my %args = @_;
894 my $payload = $args{payload};
895 my $alg = $args{alg};
896 my $header = $args{extra_headers} ? \%{$args{extra_headers}} : {};
897 die( "JWS: alg 'none' not allowed" ) if( $alg eq 'none' && !$args{allow_none} );
898 # add claims to payload
899 _add_claims( $payload, %args ) if( ref( $payload ) eq 'HASH' );
900 # serialize payload
901 $payload = _payload_enc( $payload );
902 # compress payload
903 # may set some header items
904 $payload = _payload_zip( $payload, $header, $args{zip} ) if( $args{zip} );
905 # encode payload
906 my $b64u_payload = encode_b64u( $payload );
907 # prepare header
908 $header->{alg} = $alg;
909 # encode header
910 my $j = JSON->new->allow_nonref->allow_blessed->convert_blessed;
911 # my $json_header = encode_json( $header );
912 my $json_header = $j->encode( $header );
913 my $b64u_header = encode_b64u( $json_header );
914 # key
915 die( "JWS: missing 'key'" ) if( !$args{key} && $alg ne 'none' );
916 my $key = defined( $args{keypass} ) ? [ $args{key}, $args{keypass} ] : $args{key};
917 # sign header
918 my $b64u_signature = _sign_jws( $b64u_header, $b64u_payload, $alg, $key );
919 return( $b64u_header, $b64u_payload, $b64u_signature );
920 }
921  
922 sub _decode_jws
923 {
924 my( $b64u_header, $b64u_payload, $b64u_sig, $unprotected_header, %args ) = @_;
925 my $header = _b64u_to_hash( $b64u_header );
926 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Decoded header is: ", Dumper( $header ), "\n" ) if( $args{debug} );
927 die( "JWS: invalid header part" ) if( $b64u_header && !$header );
928 $unprotected_header = {} if( ref( $unprotected_header ) ne 'HASH' );
929  
930 if( !$args{ignore_signature} )
931 {
932 my $alg = $header->{alg};
933 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Checking signature with algorithm '$alg'\n" ) if( $args{debug} );
934 die( "JWS: missing header 'alg'" ) unless( $alg );
935 die( "JWS: alg 'none' not allowed" ) if( $alg eq 'none' && !$args{allow_none} );
936 die( "JWS: alg 'none' expects no signature" ) if( $alg eq 'none' && defined( $b64u_sig ) && length( $b64u_sig ) > 0 );
937  
938 my $aa = $args{accepted_alg};
939 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Accepted algorithms are: ", Dumper( $aa ), "\n" ) if( $args{debug} );
940 if( ref( $aa ) eq 'Regexp' )
941 {
942 die( "JWS: alg '$alg' does not match accepted_alg" ) if( $alg !~ $aa );
943 }
944 elsif( ref( $aa ) eq 'ARRAY' )
945 {
946 my %acca = map { $_ => 1 } @$aa;
947 die( "JWS: alg '$alg' not in accepted_alg" ) if( !$acca{$alg} );
948 }
949 elsif( defined( $aa ) )
950 {
951 die( "JWS: alg '$alg' not accepted_alg" ) if( $aa ne $alg );
952 }
953  
954 if( $alg ne 'none' )
955 {
956 my $key;
957 if( exists( $args{key} ) )
958 {
959 $key = defined( $args{keypass} ) ? [ $args{key}, $args{keypass} ] : $args{key};
960 }
961 elsif( exists( $args{kid_keys} ) )
962 {
963 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Using kid_keys of ", Dumper( $args{kid_keys} ), "\n" ) if( $args{debug} );
964 # BEWARE: stricter approach since 0.023
965 # when 'kid_keys' specified it croaks if header doesn't contain 'kid' value or if 'kid' wasn't found in 'kid_keys'
966 my $kid = exists( $header->{kid} ) ? $header->{kid} : $unprotected_header->{kid};
967 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Kid found in header '$kid', looking it up\n" ) if( $args{debug} );
968 my $k = _kid_lookup( $kid, $args{kid_keys}, $alg );
969 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Could not find kid among keys provided.\n" ) if( $args{debug} && !defined( $k ) );
970 die( "JWS: kid_keys lookup failed" ) if( !defined( $k ) );
971 $key = $k;
972 }
973 elsif( $args{key_from_jwk_header} )
974 {
975 # BEWARE: stricter approach since 0.023
976 # - header 'jwk' is by default ignored (unless given: key_from_jwk_header => 1)
977 # - only RSA/ECDSA public keys are accepted
978 my $k = $header->{jwk};
979 die( "JWS: jwk header does not contain a key" ) if( !defined( $k ) || ref( $k ) ne 'HASH' || !defined( $k->{kty} ) );
980 die( "JWS: jwk header allowed only for RSA/ECDSA" ) if( $alg !~ /^(RS|PS|ES)/ || $k->{kty} !~ /^(RSA|EC)$/ );
981 die( "JWS: jwk header must be a public key" ) if( $k->{d} || $k->{p} || $k->{q} || $k->{dp} || $k->{dq} || $k->{qi} );
982 $key = $k;
983 }
984 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Key set to '$key'\n" ) if( $args{debug} );
985 die( "JWS: missing key" ) if( !defined( $key ) );
986  
987 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Verifying the JWS\n" ) if( $args{debug} );
988 my $valid = _verify_jws( $b64u_header, $b64u_payload, $b64u_sig, $alg, $key );
989 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: JWS found to be invalid!\n" ) if( $args{debug} && !$valid );
990 die( "JWS: invalid signature" ) if( !$valid );
991 }
992 }
993 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Decoding payload...\n" ) if( $args{debug} );
994 my $payload = decode_b64u( $b64u_payload );
995 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Decoded payload is: ", Dumper( $payload ), "\n" ) if( $args{debug} );
996 die( "JWS: invalid payload part" ) if( $b64u_payload && !$payload );
997 $payload = _payload_unzip( $payload, $header->{zip} ) if( $header->{zip} );
998 $payload = _payload_dec( $payload, $args{decode_payload} );
999 # croaks on error
1000 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Verify claim of payload\n" ) if( $args{debug} );
1001 _verify_claims( $payload, %args ) if( ref( $payload ) eq 'HASH' );
1002 print( STDERR __PACKAGE__ . "::_decode_jws() [", __LINE__, "]: Returning header and payload verified\n" ) if( $args{debug} );
1003 # merge headers
1004 $header = { %$unprotected_header, %$header };
1005 return( $header, $payload );
1006 }
1007  
1008 1;
1009 # NOTE: pod
1010 #### URLs
1011 # https://metacpan.org/pod/JSON::WebToken
1012 # https://metacpan.org/pod/Mojo::JWT
1013 # https://bitbucket.org/b_c/jose4j/wiki/JWE%20Examples
1014 # https://bitbucket.org/b_c/jose4j/wiki/JWS%20Examples
1015 # https://github.com/dvsekhvalnov/jose-jwt/tree/master/JWT/jwe
1016 # https://github.com/progrium/ruby-jwt
1017 # https://github.com/jpadilla/pyjwt/
1018  
1019 =pod
1020  
1021 =head1 NAME
1022  
1023 Net::API::REST::JWT - JSON Web Token (JWT, JWS, JWE) as defined by RFC7519, RFC7515, RFC7516
1024  
1025 =head1 SYNOPSIS
1026  
1027 # encoding
1028 use Net::API::REST::JWT qw( encode_jwt );
1029 my $jws_token = encode_jwt( payload => $data, alg => 'HS256', key => 'secret' );
1030 my $jwe_token = encode_jwt(
1031 payload => $data,
1032 alg => 'PBES2-HS256+A128KW',
1033 enc => 'A128GCM',
1034 key => 'secret'
1035 );
1036  
1037 # decoding
1038 use Net::API::REST::JWT qw( decode_jwt );
1039 my $data1 = decode_jwt( token => $jws_token, key => 'secret' );
1040 my $data2 = decode_jwt( token => $jwe_token, key => 'secret' );
1041  
1042 =head1 DESCRIPTION
1043  
1044 This is purely a copy of Crypt::JWT module with the key exception that it uses the L<JSON::PP> module instead of the L<JSON::XS> one. The reason why is due to some incompatibility with some version of ModPerl. Under this edge case, even if one passes an hash to encode_jwt, it fails to recognise the hash reference and produces the error:
1045  
1046 hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)
1047  
1048 Using L<JSON::PP> alleviates this problem. There is no other change in the code, and the current version of L<Crypt::JWT> used is 0.024
1049  
1050 Implements B<JSON Web Token (JWT)> - L<https://tools.ietf.org/html/rfc7519>.
1051 The implementation covers not only B<JSON Web Signature (JWS)> - L<https://tools.ietf.org/html/rfc7515>,
1052 but also B<JSON Web Encryption (JWE)> - L<https://tools.ietf.org/html/rfc7516>.
1053  
1054 The module implements B<all (100%) algorithms> defined in L<https://tools.ietf.org/html/rfc7518> - B<JSON Web Algorithms (JWA)>.
1055  
1056 This module supports B<Compact JWS/JWE> and B<Flattened JWS/JWE JSON> serialization, general JSON serialization is not supported yet.
1057  
1058 =head1 EXPORT
1059  
1060 Nothing is exported by default.
1061  
1062 You can export selected functions:
1063  
1064 use Net::API::REST::JWT qw(decode_jwt encode_jwt);
1065  
1066 Or all of them at once:
1067  
1068 use Net::API::REST::JWT ':all';
1069  
1070 =head1 FUNCTIONS
1071  
1072 =head2 decode_jwt
1073  
1074 my $data = decode_jwt(%named_args);
1075  
1076 Named arguments:
1077  
1078 =over
1079  
1080 =item token
1081  
1082 Mandatory argument, a string with either JWS or JWE JSON Web Token.
1083  
1084 ### JWS token example (3 segments)
1085 $t = "eyJhbGciOiJIUzI1NiJ9.dGVzdA.ujBihtLSr66CEWqN74SpLUkv28lra_CeHnxLmLNp4Jo";
1086 my $data = decode_jwt(token=>$t, key=>$k);
1087  
1088 ### JWE token example (5 segments)
1089 $t = "eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiQTEyOEtXIn0.UusxEbzhGkORxTRq0xkFKhvzPrXb9smw.VGfOuq0Fxt6TsdqLZUpnxw.JajIQQ.pkKZ7MHS0XjyGmRsqgom6w";
1090 my $data = decode_jwt(token=>$t, key=>$k);
1091  
1092 =item key
1093  
1094 A key used for token decryption (JWE) or token signature validation (JWS).
1095 The value depends on the C<alg> token header value.
1096  
1097 JWS alg header key value
1098 ------------------ ----------------------------------
1099 none no key required
1100 HS256 string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1101 HS384 dtto
1102 HS512 dtto
1103 RS256 public RSA key, perl HASH ref with JWK key structure,
1104 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1105 object: Crypt::PK::RSA, Crypt::OpenSSL::RSA, Crypt::X509 or Crypt::OpenSSL::X509
1106 RS384 public RSA key, see RS256
1107 RS512 public RSA key, see RS256
1108 PS256 public RSA key, see RS256
1109 PS384 public RSA key, see RS256
1110 PS512 public RSA key, see RS256
1111 ES256 public ECC key, perl HASH ref with JWK key structure,
1112 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1113 an instance of Crypt::PK::ECC
1114 ES384 public ECC key, see ES256
1115 ES512 public ECC key, see ES256
1116  
1117 JWE alg header key value
1118 ------------------ ----------------------------------
1119 dir string (raw octects) or perl HASH ref with JWK, kty=>'oct', length depends on 'enc' algorithm
1120 A128KW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct')
1121 A192KW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct')
1122 A256KW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct')
1123 A128GCMKW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct')
1124 A192GCMKW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct')
1125 A256GCMKW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct')
1126 PBES2-HS256+A128KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1127 PBES2-HS384+A192KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1128 PBES2-HS512+A256KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1129 RSA-OAEP private RSA key, perl HASH ref with JWK key structure,
1130 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1131 an instance of Crypt::PK::RSA or Crypt::OpenSSL::RSA
1132 RSA-OAEP-256 private RSA key, see RSA-OAEP
1133 RSA1_5 private RSA key, see RSA-OAEP
1134 ECDH-ES private ECC key, perl HASH ref with JWK key structure,
1135 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1136 an instance of Crypt::PK::ECC
1137 ECDH-ES+A128KW private ECC key, see ECDH-ES
1138 ECDH-ES+A192KW private ECC key, see ECDH-ES
1139 ECDH-ES+A256KW private ECC key, see ECDH-ES
1140  
1141 Example using the key from C<jwk> token header:
1142  
1143 my $data = decode_jwt(token=>$t, key_from_jwk_header=>1);
1144 my ($header, $data) = decode_jwt(token=>$t, decode_header=>1, key_from_jwk_header=>1);
1145  
1146 Examples with raw octet keys:
1147  
1148 #string
1149 my $data = decode_jwt(token=>$t, key=>'secretkey');
1150 #binary key
1151 my $data = decode_jwt(token=>$t, key=>pack("H*", "788A6E38F36B7596EF6A669E94"));
1152 #perl HASH ref with JWK structure (key type 'oct')
1153 my $data = decode_jwt(token=>$t, key=>{kty=>'oct', k=>"GawgguFyGrWKav7AX4VKUg"});
1154  
1155 Examples with RSA keys:
1156  
1157 my $pem_key_string = <<'EOF';
1158 -----BEGIN PRIVATE KEY-----
1159 MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoVm/Sl5r+Ofky
1160 jioRSZK26GW6WyjyfWKddsSi13/NOtCn0rRErSF/u3QrgGMpWFqKohqbi1VVC+SZ
1161 ...
1162 8c1vm2YFafgdkSk9Qd1oU2Fv1aOQy4VovOFzJ3CcR+2r7cbRfcpLGnintHtp9yek
1163 02p+d5g4OChfFNDhDtnIqjvY
1164 -----END PRIVATE KEY-----
1165 EOF
1166  
1167 my $jwk_key_json_string = '{"kty":"RSA","n":"0vx7agoebG...L6tSoc_BJECP","e":"AQAB"}';
1168  
1169 #a reference to SCALAR string with PEM or DER or JSON/JWK data,
1170 my $data = decode_jwt(token=>$t, key=>\$pem_key_string);
1171 my $data = decode_jwt(token=>$t, key=>\$der_key_string);
1172 my $data = decode_jwt(token=>$t, key=>\$jwk_key_json_string);
1173  
1174 #instance of Crypt::PK::RSA
1175 my $data = decode_jwt(token=>$t, key=>Crypt::PK::RSA->new('keyfile.pem'));
1176 my $data = decode_jwt(token=>$t, key=>Crypt::PK::RSA->new(\$pem_key_string));
1177  
1178 #instance of Crypt::OpenSSL::RSA
1179 my $data = decode_jwt(token=>$t, key=>Crypt::OpenSSL::RSA->new_private_key($pem_key_string));
1180  
1181 #instance of Crypt::X509 (public key only)
1182 my $data = decode_jwt(token=>$t, key=>Crypt::X509->new(cert=>$cert));
1183  
1184 #instance of Crypt::OpenSSL::X509 (public key only)
1185 my $data = decode_jwt(token=>$t, key=>Crypt::OpenSSL::X509->new_from_file('cert.pem'));
1186 my $data = decode_jwt(token=>$t, key=>Crypt::OpenSSL::X509->new_from_string($cert));
1187  
1188 #perl HASH ref with JWK structure (key type 'RSA')
1189 my $rsa_priv = {
1190 kty => "RSA",
1191 n => "0vx7agoebGcQSuuPiLJXZpt...eZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
1192 e => "AQAB",
1193 d => "X4cTteJY_gn4FYPsXB8rdXi...FLN5EEaG6RoVH-HLKD9Mdx5ooGURknhnrRwUkC7h5fJLMWbFAKLWY2v7B6NqSzUvx0_YSf",
1194 p => "83i-7IvMGXoMXCskv73TKr8...Z27zvoj6pbUQyLPBQxtPnwD20-60eTmD2ujMt5PoMrm8RmNhVWtjjMmMjOpSicFHjXOuVI",
1195 q => "3dfOR9cuYq-0S-mkFLzgItg...q3hWeMuG0ouqnb3obLyuqjVZQ1dIrdgTnCdYzBcOW5r37AFXjift_NGiovonzhKpoVVS78",
1196 dp => "G4sPXkc6Ya9y8oJW9_ILj4...zi_H7TkS8x5SdX3oE0oiYwxIiemTAu0UOa5pgFGyJ4c8t2VF40XRugKTP8akhFo5tA77Qe",
1197 dq => "s9lAH9fggBsoFR8Oac2R_E...T2kGOhvIllTE1efA6huUvMfBcpn8lqW6vzzYY5SSF7pMd_agI3G8IbpBUb0JiraRNUfLhc",
1198 qi => "GyM_p6JrXySiz1toFgKbWV...4ypu9bMWx3QJBfm0FoYzUIZEVEcOqwmRN81oDAaaBk0KWGDjJHDdDmFW3AN7I-pux_mHZG",
1199 };
1200 my $data = decode_jwt(token=>$t, key=>$rsa_priv});
1201  
1202 Examples with ECC keys:
1203  
1204 my $pem_key_string = <<'EOF';
1205 -----BEGIN EC PRIVATE KEY-----
1206 MHcCAQEEIBG1c3z52T8XwMsahGVdOZWgKCQJfv+l7djuJjgetdbDoAoGCCqGSM49
1207 AwEHoUQDQgAEoBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxG+9DLFmRSM
1208 lBQ9T/RsLLc+PmpB1+7yPAR+oR5gZn3kJQ==
1209 -----END EC PRIVATE KEY-----
1210 EOF
1211  
1212 my $jwk_key_json_string = '{"kty":"EC","crv":"P-256","x":"MKB..7D4","y":"4Et..FyM"}';
1213  
1214 #a reference to SCALAR string with PEM or DER or JSON/JWK data,
1215 my $data = decode_jwt(token=>$t, key=>\$pem_key_string);
1216 my $data = decode_jwt(token=>$t, key=>\$der_key_string);
1217 my $data = decode_jwt(token=>$t, key=>\$jwk_key_json_string);
1218  
1219 #instance of Crypt::PK::ECC
1220 my $data = decode_jwt(token=>$t, key=>Crypt::PK::ECC->new('keyfile.pem'));
1221 my $data = decode_jwt(token=>$t, key=>Crypt::PK::ECC->new(\$pem_key_string));
1222  
1223 #perl HASH ref with JWK structure (key type 'EC')
1224 my $ecc_priv = {
1225 kty => "EC",
1226 crv => "P-256",
1227 x => "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
1228 y => "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
1229 d => "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE",
1230 };
1231 my $data = decode_jwt(token=>$t, key=>$ecc_priv});
1232  
1233 =item keypass
1234  
1235 When 'key' parameter is an encrypted private RSA or ECC key this optional parameter may contain a password for private key decryption.
1236  
1237 =item kid_keys
1238  
1239 This parametes can be either a JWK Set JSON string (see RFC7517) or a perl HASH ref with JWK Set structure like this:
1240  
1241 my $keylist = {
1242 keys => [
1243 { kid=>"key1", kty=>"oct", k=>"GawgguFyGrWKav7AX4VKUg" },
1244 { kid=>"key2", kty=>"oct", k=>"ulxLGy4XqhbpkR5ObGh1gX" },
1245 ]
1246 };
1247 my $payload = decode_jwt(token=>$t, kid_keys=>$keylist);
1248  
1249 The structure described above is used e.g. by L<https://www.googleapis.com/oauth2/v2/certs>
1250  
1251 use Mojo::UserAgent;
1252 my $ua = Mojo::UserAgent->new;
1253 my $google_keys => $ua->get('https://www.googleapis.com/oauth2/v2/certs')->result->json;
1254 my $payload = decode_jwt(token => $t, kid_keys => $google_keys);
1255  
1256 B<SINCE 0.019> we also support alternative structure used e.g. by L<https://www.googleapis.com/oauth2/v1/certs>:
1257  
1258 use LWP::Simple;
1259 my $google_certs = get('https://www.googleapis.com/oauth2/v1/certs');
1260 my $payload = decode_jwt(token => $t, kid_keys => $google_certs);
1261  
1262 When the token header contains C<kid> item the corresponding key is looked up in C<kid_keys> list and used for token
1263 decoding (you do not need to pass the explicit key via C<key> parameter).
1264  
1265 B<INCOMPATIBLE CHANGE in 0.023:> When C<kid_keys> is specified it croaks if token header does not contain C<kid> value or
1266 if C<kid> was not found in C<kid_keys>.
1267  
1268 =item key_from_jwk_header
1269  
1270 B<SINCE 0.023>
1271  
1272 C<1> - use C<jwk> header value for validating JWS signature if neither C<key> nor C<kid_keys> specified, B<BEWARE: DANGEROUS, UNSECURE!!!>
1273  
1274 C<0> (default) - ignore C<jwk> header value when validating JWS signature
1275  
1276 Keep in mind that enabling C<key_from_jwk_header> requires C<jwk> header to exist and be an valid RSA/ECDSA public key (otherwise it croaks).
1277  
1278 =item allow_none
1279  
1280 C<1> - accept JWS tokens with C<none> 'alg' header value (which means that token has no signature), B<BEWARE: DANGEROUS, UNSECURE!!!>
1281  
1282 C<0> (default) - do not allow JWS with C<none> 'alg' header value
1283  
1284 =item ignore_signature
1285  
1286 C<1> - do not check signature on JWS tokens, B<BEWARE: DANGEROUS, UNSECURE!!!>
1287  
1288 C<0> (default) - check signature on JWS tokens
1289  
1290 =item accepted_alg
1291  
1292 C<undef> (default) means accept all 'alg' algorithms except 'none' (for accepting 'none' use C<allow_none>)
1293  
1294 C<string> name of accepted 'alg' algorithm (only one)
1295  
1296 C<ARRAY ref> a list of accepted 'alg' algorithms
1297  
1298 C<Regexp> that has to match 'alg' algorithm name
1299  
1300 my $payload = decode_jwt(token=>$t, key=>$k, accepted_alg=>'HS256');
1301 #or
1302 my $payload = decode_jwt(token=>$t, key=>$k, accepted_alg=>['HS256','HS384']);
1303 #or
1304 my $payload = decode_jwt(token=>$t, key=>$k, accepted_alg=>qr/^HS(256|384|512)$/);
1305  
1306 =item accepted_enc
1307  
1308 C<undef> (default) means accept all 'enc' algorithms
1309  
1310 C<string> name of accepted 'enc' algorithm (only one)
1311  
1312 C<ARRAY ref> a list of accepted 'enc' algorithms
1313  
1314 C<Regexp> that has to match 'enc' algorithm name
1315  
1316 my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>'A192GCM');
1317 #or
1318 my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>['A192GCM','A256GCM']);
1319 #or
1320 my $payload = decode_jwt(token=>$t, key=>$k, accepted_enc=>qr/^A(128|192|256)GCM$/);
1321  
1322 =item decode_payload
1323  
1324 C<0> - do not decode payload, return it as a raw string (octects).
1325  
1326 C<1> - decode payload from JSON string, return it as perl hash ref (or array ref) - decode_json failure means fatal error (croak).
1327  
1328 C<undef> (default) - if possible decode payload from JSON string, if decode_json fails return payload as a raw string (octets).
1329  
1330 =item decode_header
1331  
1332 C<0> (default) - do not return decoded header as a return value of decode_jwt()
1333  
1334 C<1> - return decoded header as a return value of decode_jwt()
1335  
1336 my $payload = decode_jwt(token=>$t, key=>$k);
1337 #or
1338 my ($header, $payload) = decode_jwt(token=>$t, key=>$k, decode_header=>1);
1339  
1340 =item verify_iss
1341  
1342 B<INCOMPATIBLE CHANGE in 0.024:> If C<verify_iss> is specified and
1343 claim C<iss> (Issuer) is completely missing it is a failure since 0.024
1344  
1345 C<CODE ref> - subroutine (with 'iss' claim value passed as argument) should return C<true> otherwise verification fails
1346  
1347 C<Regexp ref> - 'iss' claim value has to match given regexp otherwise verification fails
1348  
1349 C<undef> (default) - do not verify 'iss' claim
1350  
1351 =item verify_aud
1352  
1353 B<INCOMPATIBLE CHANGE in 0.024:> If C<verify_iss> is specified and
1354 claim C<aud> (Audience) is completely missing it is a failure since 0.024
1355  
1356 C<CODE ref> - subroutine (with 'aud' claim value passed as argument) should return C<true> otherwise verification fails
1357  
1358 C<Regexp ref> - 'aud' claim value has to match given regexp otherwise verification fails
1359  
1360 C<undef> (default) - do not verify 'aud' claim
1361  
1362 =item verify_sub
1363  
1364 B<INCOMPATIBLE CHANGE in 0.024:> If C<verify_iss> is specified and
1365 claim C<sub> (Subject) is completely missing it is a failure since 0.024
1366  
1367 C<CODE ref> - subroutine (with 'sub' claim value passed as argument) should return C<true> otherwise verification fails
1368  
1369 C<Regexp ref> - 'sub' claim value has to match given regexp otherwise verification fails
1370  
1371 C<undef> (default) - do not verify 'sub' claim
1372  
1373 =item verify_jti
1374  
1375 B<INCOMPATIBLE CHANGE in 0.024:> If C<verify_iss> is specified and
1376 claim C<jti> (JWT ID) is completely missing it is a failure since 0.024
1377  
1378 C<CODE ref> - subroutine (with 'jti' claim value passed as argument) should return C<true> otherwise verification fails
1379  
1380 C<Regexp ref> - 'jti' claim value has to match given regexp otherwise verification fails
1381  
1382 C<undef> (default) - do not verify 'jti' claim
1383  
1384 =item verify_iat
1385  
1386 C<undef> - Issued At 'iat' claim must be valid (not in the future) if present
1387  
1388 C<0> (default) - ignore 'iat' claim
1389  
1390 C<1> - require valid 'iat' claim
1391  
1392 =item verify_nbf
1393  
1394 C<undef> (default) - Not Before 'nbf' claim must be valid if present
1395  
1396 C<0> - ignore 'nbf' claim
1397  
1398 C<1> - require valid 'nbf' claim
1399  
1400 =item verify_exp
1401  
1402 C<undef> (default) - Expiration Time 'exp' claim must be valid if present
1403  
1404 C<0> - ignore 'exp' claim
1405  
1406 C<1> - require valid 'exp' claim
1407  
1408 =item leeway
1409  
1410 Tolerance in seconds related to C<verify_exp>, C<verify_nbf> and C<verify_iat>. Default is C<0>.
1411  
1412 =item ignore_claims
1413  
1414 C<1> - do not check claims (iat, exp, nbf, iss, aud, sub, jti), B<BEWARE: DANGEROUS, UNSECURE!!!>
1415  
1416 C<0> (default) - check claims
1417  
1418 =back
1419  
1420 =head2 encode_jwt
1421  
1422 my $token = encode_jwt(%named_args);
1423  
1424 Named arguments:
1425  
1426 =over
1427  
1428 =item payload
1429  
1430 Value of this mandatory parameter can be a string/buffer or HASH ref or ARRAY ref
1431  
1432 my $token = encode_jwt(payload=>"any raw data", key=>$k, alg=>'HS256');
1433 #or
1434 my $token = encode_jwt(payload=>{a=>1,b=>2}, key=>$k, alg=>'HS256');
1435 #or
1436 my $token = encode_jwt(payload=>[11,22,33,44], key=>$k, alg=>'HS256');
1437  
1438 HASH refs and ARRAY refs payloads are serialized as JSON strings
1439  
1440 =item alg
1441  
1442 The 'alg' header value is mandatory for both JWE and JWS tokens.
1443  
1444 Supported JWE 'alg' algorithms:
1445  
1446 dir
1447 A128KW
1448 A192KW
1449 A256KW
1450 A128GCMKW
1451 A192GCMKW
1452 A256GCMKW
1453 PBES2-HS256+A128KW
1454 PBES2-HS384+A192KW
1455 PBES2-HS512+A256KW
1456 RSA-OAEP
1457 RSA-OAEP-256
1458 RSA1_5
1459 ECDH-ES+A128KW
1460 ECDH-ES+A192KW
1461 ECDH-ES+A256KW
1462 ECDH-ES
1463  
1464 Supported JWS algorithms:
1465  
1466 none ... no integrity (NOTE: disabled by default)
1467 HS256 ... HMAC+SHA256 integrity
1468 HS384 ... HMAC+SHA384 integrity
1469 HS512 ... HMAC+SHA512 integrity
1470 RS256 ... RSA+PKCS1-V1_5 + SHA256 signature
1471 RS384 ... RSA+PKCS1-V1_5 + SHA384 signature
1472 RS512 ... RSA+PKCS1-V1_5 + SHA512 signature
1473 PS256 ... RSA+PSS + SHA256 signature
1474 PS384 ... RSA+PSS + SHA384 signature
1475 PS512 ... RSA+PSS + SHA512 signature
1476 ES256 ... ECDSA + SHA256 signature
1477 ES384 ... ECDSA + SHA384 signature
1478 ES512 ... ECDSA + SHA512 signature
1479  
1480 =item enc
1481  
1482 The 'enc' header is mandatory for JWE tokens.
1483  
1484 Supported 'enc' algorithms:
1485  
1486 A128GCM
1487 A192GCM
1488 A256GCM
1489 A128CBC-HS256
1490 A192CBC-HS384
1491 A256CBC-HS512
1492  
1493 =item key
1494  
1495 A key used for token encryption (JWE) or token signing (JWS). The value depends on C<alg> token header value.
1496  
1497 JWS alg header key value
1498 ------------------ ----------------------------------
1499 none no key required
1500 HS256 string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1501 HS384 dtto
1502 HS512 dtto
1503 RS256 private RSA key, perl HASH ref with JWK key structure,
1504 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1505 object: Crypt::PK::RSA, Crypt::OpenSSL::RSA, Crypt::X509 or Crypt::OpenSSL::X509
1506 RS384 private RSA key, see RS256
1507 RS512 private RSA key, see RS256
1508 PS256 private RSA key, see RS256
1509 PS384 private RSA key, see RS256
1510 PS512 private RSA key, see RS256
1511 ES256 private ECC key, perl HASH ref with JWK key structure,
1512 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1513 an instance of Crypt::PK::ECC
1514 ES384 private ECC key, see ES256
1515 ES512 private ECC key, see ES256
1516  
1517 JWE alg header key value
1518 ------------------ ----------------------------------
1519 dir string (raw octects) or perl HASH ref with JWK, kty=>'oct', length depends on 'enc' algorithm
1520 A128KW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct')
1521 A192KW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct')
1522 A256KW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct')
1523 A128GCMKW string (raw octects) 16 bytes (or perl HASH ref with JWK, kty=>'oct')
1524 A192GCMKW string (raw octects) 24 bytes (or perl HASH ref with JWK, kty=>'oct')
1525 A256GCMKW string (raw octects) 32 bytes (or perl HASH ref with JWK, kty=>'oct')
1526 PBES2-HS256+A128KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1527 PBES2-HS384+A192KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1528 PBES2-HS512+A256KW string (raw octects) of any length (or perl HASH ref with JWK, kty=>'oct')
1529 RSA-OAEP public RSA key, perl HASH ref with JWK key structure,
1530 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1531 an instance of Crypt::PK::RSA or Crypt::OpenSSL::RSA
1532 RSA-OAEP-256 public RSA key, see RSA-OAEP
1533 RSA1_5 public RSA key, see RSA-OAEP
1534 ECDH-ES public ECC key, perl HASH ref with JWK key structure,
1535 a reference to SCALAR string with PEM or DER or JSON/JWK data,
1536 an instance of Crypt::PK::ECC
1537 ECDH-ES+A128KW public ECC key, see ECDH-ES
1538 ECDH-ES+A192KW public ECC key, see ECDH-ES
1539 ECDH-ES+A256KW public ECC key, see ECDH-ES
1540  
1541 =item keypass
1542  
1543 When 'key' parameter is an encrypted private RSA or ECC key this optional parameter may contain a password for private key decryption.
1544  
1545 =item allow_none
1546  
1547 C<1> - allow JWS with C<none> 'alg' header value (which means that token has no signature), B<BEWARE: DANGEROUS, UNSECURE!!!>
1548  
1549 C<0> (default) - do not allow JWS with C<none> 'alg' header value
1550  
1551 =item extra_headers
1552  
1553 This optional parameter may contain a HASH ref with items that will be added to JWT header.
1554  
1555 If you want to use PBES2-based 'alg' like C<PBES2-HS512+A256KW> you can set PBES2 salt len (p2s) in bytes and
1556 iteration count (p2c) via C<extra_headers> like this:
1557  
1558 my $token = encode_jwt(payload=>$p, key=>$k, alg=>'PBES2-HS512+A256KW', extra_headers=>{p2c=8000, p2s=>32});
1559 #NOTE: handling of p2s header is a special case, in the end it is replaced with the generated salt
1560  
1561 =item unprotected_headers
1562  
1563 A hash with additional integrity unprotected headers - JWS and JWE (not available for C<compact> serialization);
1564  
1565 =item shared_unprotected_headers
1566  
1567 A hash with additional integrity unprotected headers - JWE only (not available for C<compact> serialization);
1568  
1569 =item aad
1570  
1571 Additional Authenticated Data - scalar value with any (even raw octects) data - JWE only (not available for C<compact> serialization);
1572  
1573 =item serialization
1574  
1575 Specify serialization method: C<compat> (= default) for Compact JWS/JWE serialization or C<flattened> for Flattened JWS/JWE JSON serialization.
1576  
1577 General JSON serialization is not supported yet.
1578  
1579 =item zip
1580  
1581 Compression method, currently 'deflate' is the only one supported. C<undef> (default) means no compression.
1582  
1583 my $token = encode_jwt(payload=>$p, key=>$k, alg=>'HS256', zip=>'deflate');
1584 #or define compression level
1585 my $token = encode_jwt(payload=>$p, key=>$k, alg=>'HS256', zip=>['deflate', 9]);
1586  
1587 =item auto_iat
1588  
1589 C<1> - set 'iat' (Issued At) claim to current time (epoch seconds since 1970) at the moment of token encoding
1590  
1591 C<0> (default) - do not set 'iat' claim
1592  
1593 NOTE: claims are part of the payload and can be used only if the payload is a HASH ref!
1594  
1595 =item relative_exp
1596  
1597 Set 'exp' claim (Expiration Time) to current time + C<relative_exp> value (in seconds).
1598  
1599 NOTE: claims are part of the payload and can be used only if the payload is a HASH ref!
1600  
1601 =item relative_nbf
1602  
1603 Set 'nbf' claim (Not Before) to current time + C<relative_nbf> value (in seconds).
1604  
1605 NOTE: claims are part of the payload and can be used only if the payload is a HASH ref!
1606  
1607 =back
1608  
1609 =head1 SEE ALSO
1610  
1611 L<Crypt::Cipher::AES>, L<Crypt::AuthEnc::GCM>, L<Crypt::PK::RSA>, L<Crypt::PK::ECC>, L<Crypt::KeyDerivation>, L<Crypt::KeyWrap>
1612  
1613 =head1 LICENSE
1614  
1615 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
1616  
1617 =head1 COPYRIGHT
1618  
1619 Copyright (c) 2015 DCIT, a.s. L<http://www.dcit.cz> / Karel Miko