1 /*! jws-3.3.1 (c) 2013-2015 Kenji Urushima | kjur.github.com/jsrsasign/license 2 */ 3 /* 4 * jws.js - JSON Web Signature(JWS) and JSON Web Token(JWT) Class 5 * 6 * version: 3.3.1 (2015 Oct 14) 7 * 8 * Copyright (c) 2010-2015 Kenji Urushima (kenji.urushima@gmail.com) 9 * 10 * This software is licensed under the terms of the MIT License. 11 * http://kjur.github.com/jsrsasign/license/ 12 * 13 * The above copyright and license notice shall be 14 * included in all copies or substantial portions of the Software. 15 */ 16 17 /** 18 * @fileOverview 19 * @name jws-3.3.js 20 * @author Kenji Urushima kenji.urushima@gmail.com 21 * @version 3.3.1 (2015-Oct-14) 22 * @since jsjws 1.0, jsrsasign 4.8.0 23 * @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a> 24 */ 25 26 if (typeof KJUR == "undefined" || !KJUR) KJUR = {}; 27 28 /** 29 * kjur's JSON Web Signature/Token(JWS/JWT) library name space 30 * <p> 31 * This namespace privides following JWS/JWS related classes. 32 * <ul> 33 * <li>{@link KJUR.jws.JWS} - JSON Web Signature/Token(JWS/JWT) class</li> 34 * <li>{@link KJUR.jws.JWSJS} - JWS JSON Serialization(JWSJS) class</li> 35 * <li>{@link KJUR.jws.IntDate} - UNIX origin time utility class</li> 36 * </ul> 37 * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. 38 * </p> 39 * @name KJUR.jws 40 * @namespace 41 */ 42 if (typeof KJUR.jws == "undefined" || !KJUR.jws) KJUR.jws = {}; 43 44 /** 45 * JSON Web Signature(JWS) class.<br/> 46 * @name KJUR.jws.JWS 47 * @class JSON Web Signature(JWS) class 48 * @see <a href="http://kjur.github.com/jsjws/">'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/</a> 49 * @see <a href="http://kjur.github.com/jsrsasigns/">'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/</a> 50 * @see <a href="http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-14">IETF I-D JSON Web Algorithms (JWA)</a> 51 * @since jsjws 1.0 52 * @description 53 * This class provides JSON Web Signature(JWS)/JSON Web Token(JWT) signing and validation. 54 * <h4>Supported Algorithms</h4> 55 * Here is supported algorithm names for {@link KJUR.jws.JWS.sign} and {@link KJUR.jws.JWS.verify} 56 * methods. 57 * <table> 58 * <tr><th>alg value</th><th>spec requirement</th><th>jsjws support</th></tr> 59 * <tr><td>HS256</td><td>REQUIRED</td><td>SUPPORTED</td></tr> 60 * <tr><td>HS384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 61 * <tr><td>HS512</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 62 * <tr><td>RS256</td><td>RECOMMENDED</td><td>SUPPORTED</td></tr> 63 * <tr><td>RS384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 64 * <tr><td>RS512</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 65 * <tr><td>ES256</td><td>RECOMMENDED+</td><td>SUPPORTED</td></tr> 66 * <tr><td>ES384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 67 * <tr><td>ES512</td><td>OPTIONAL</td><td>-</td></tr> 68 * <tr><td>PS256</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 69 * <tr><td>PS384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 70 * <tr><td>PS512</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 71 * <tr><td>none</td><td>REQUIRED</td><td>SUPPORTED(signature generation only)</td></tr> 72 * </table> 73 * <dl> 74 * <dt><b>NOTE1</b> 75 * <dd>HS384 is supported since jsjws 3.0.2 with jsrsasign 4.1.4. 76 * <dt><b>NOTE2</b> 77 * <dd>Some deprecated methods have been removed since jws 3.3 of jsrsasign 4.10.0. 78 * Removed methods are following: 79 * <ul> 80 * <li>JWS.verifyJWSByNE</li> 81 * <li>JWS.verifyJWSByKey</li> 82 * <li>JWS.generateJWSByNED</li> 83 * <li>JWS.generateJWSByKey</li> 84 * <li>JWS.generateJWSByP1PrvKey</li> 85 * </ul> 86 * </dl> 87 * <b>EXAMPLE</b><br/> 88 * @example 89 * // JWS signing 90 * sJWS = KJUR.jws.JWS.sign(null, '{"alg":"HS256", "cty":"JWT"}', '{"age": 21}', "password"); 91 * // JWS validation 92 * isValid = KJUR.jws.JWS.verify('eyJjdHkiOiJKV1QiLCJhbGc...', "password"); 93 * // JWT validation 94 * isValid = KJUR.jws.JWS.verifyJWT('eyJh...', "password", { 95 * alg: ['HS256', 'HS384'], 96 * iss: ['http://foo.com'] 97 * }); 98 */ 99 KJUR.jws.JWS = function() { 100 var ns1 = KJUR.jws.JWS; 101 102 // === utility ============================================================= 103 104 /** 105 * parse JWS string and set public property 'parsedJWS' dictionary.<br/> 106 * @name parseJWS 107 * @memberOf KJUR.jws.JWS 108 * @function 109 * @param {String} sJWS JWS signature string to be parsed. 110 * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". 111 * @throws if JWS Header is a malformed JSON string. 112 * @since jws 1.1 113 */ 114 this.parseJWS = function(sJWS, sigValNotNeeded) { 115 if ((this.parsedJWS !== undefined) && 116 (sigValNotNeeded || (this.parsedJWS.sigvalH !== undefined))) { 117 return; 118 } 119 if (sJWS.match(/^([^.]+)\.([^.]+)\.([^.]+)$/) == null) { 120 throw "JWS signature is not a form of 'Head.Payload.SigValue'."; 121 } 122 var b6Head = RegExp.$1; 123 var b6Payload = RegExp.$2; 124 var b6SigVal = RegExp.$3; 125 var sSI = b6Head + "." + b6Payload; 126 this.parsedJWS = {}; 127 this.parsedJWS.headB64U = b6Head; 128 this.parsedJWS.payloadB64U = b6Payload; 129 this.parsedJWS.sigvalB64U = b6SigVal; 130 this.parsedJWS.si = sSI; 131 132 if (!sigValNotNeeded) { 133 var hSigVal = b64utohex(b6SigVal); 134 var biSigVal = parseBigInt(hSigVal, 16); 135 this.parsedJWS.sigvalH = hSigVal; 136 this.parsedJWS.sigvalBI = biSigVal; 137 } 138 139 var sHead = b64utoutf8(b6Head); 140 var sPayload = b64utoutf8(b6Payload); 141 this.parsedJWS.headS = sHead; 142 this.parsedJWS.payloadS = sPayload; 143 144 if (! ns1.isSafeJSONString(sHead, this.parsedJWS, 'headP')) 145 throw "malformed JSON string for JWS Head: " + sHead; 146 }; 147 }; 148 149 // === major static method ======================================================== 150 151 /** 152 * generate JWS signature by specified key<br/> 153 * @name sign 154 * @memberOf KJUR.jws.JWS 155 * @function 156 * @static 157 * @param {String} alg JWS algorithm name to sign and force set to sHead or null 158 * @param {String} spHead string or object of JWS Header 159 * @param {String} spPayload string or object of JWS Payload 160 * @param {String} key string of private key or mac key object to sign 161 * @param {String} pass (OPTION)passcode to use encrypted asymmetric private key 162 * @return {String} JWS signature string 163 * @since jws 3.0.0 164 * @see <a href="http://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Signature.html">jsrsasign KJUR.crypto.Signature method</a> 165 * @see <a href="http://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Mac.html">jsrsasign KJUR.crypto.Mac method</a> 166 * @description 167 * This method supports following algorithms. 168 * <table> 169 * <tr><th>alg value</th><th>spec requirement</th><th>jsjws support</th></tr> 170 * <tr><td>HS256</td><td>REQUIRED</td><td>SUPPORTED</td></tr> 171 * <tr><td>HS384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 172 * <tr><td>HS512</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 173 * <tr><td>RS256</td><td>RECOMMENDED</td><td>SUPPORTED</td></tr> 174 * <tr><td>RS384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 175 * <tr><td>RS512</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 176 * <tr><td>ES256</td><td>RECOMMENDED+</td><td>SUPPORTED</td></tr> 177 * <tr><td>ES384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 178 * <tr><td>ES512</td><td>OPTIONAL</td><td>-</td></tr> 179 * <tr><td>PS256</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 180 * <tr><td>PS384</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 181 * <tr><td>PS512</td><td>OPTIONAL</td><td>SUPPORTED</td></tr> 182 * <tr><td>none</td><td>REQUIRED</td><td>SUPPORTED(signature generation only)</td></tr> 183 * </table> 184 * <dl> 185 * <dt>NOTE1: 186 * <dd>salt length of RSAPSS signature is the same as the hash algorithm length 187 * because of <a href="http://www.ietf.org/mail-archive/web/jose/current/msg02901.html">IETF JOSE ML discussion</a>. 188 * <dt>NOTE2: 189 * <dd>To support HS384, patched version of CryptoJS is used. 190 * <a href="https://code.google.com/p/crypto-js/issues/detail?id=84">See here for detail</a>. 191 * <dt>NOTE3: 192 * From jsrsasign 4.10.0 jws 3.3.0, Way to provide password 193 * for HS* algorithm is changed. The 'key' attribute value is 194 * passed to {@link KJUR.crypto.Mac.setPassword} so please see 195 * {@link KJUR.crypto.Mac.setPassword} for detail. 196 * As for backword compatibility, if key is a string, has even length and 197 * 0..9, A-F or a-f characters, key string is treated as a hexadecimal 198 * otherwise it is treated as a raw string. 199 * <dd> 200 * </dl> 201 * <b>EXAMPLE</b><br/> 202 * @example 203 * // sign HS256 signature with password "aaa" implicitly handled as string 204 * sJWS = KJUR.jws.JWS.sign(null, {alg: "HS256", cty: "JWT"}, {age: 21}, "aaa"); 205 * // sign HS256 signature with password "6161" implicitly handled as hex 206 * sJWS = KJUR.jws.JWS.sign(null, {alg: "HS256", cty: "JWT"}, {age: 21}, "6161"); 207 * // sign HS256 signature with base64 password 208 * sJWS = KJUR.jws.JWS.sign(null, {alg: "HS256"}, {age: 21}, {b64: "Mi/8..a="}); 209 * // sign RS256 signature with PKCS#8 PEM RSA private key 210 * sJWS = KJUR.jws.JWS.sign(null, {alg: "RS256"}, {age: 21}, "-----BEGIN PRIVATE KEY..."); 211 * // sign RS256 signature with PKCS#8 PEM ECC private key with passcode 212 * sJWS = KJUR.jws.JWS.sign(null, {alg: "ES256"}, {age: 21}, 213 * "-----BEGIN PRIVATE KEY...", "keypass"); 214 * // header and payload can be passed by both string and object 215 * sJWS = KJUR.jws.JWS.sign(null, '{alg:"HS256",cty:"JWT"}', '{age:21}', "aaa"); 216 */ 217 KJUR.jws.JWS.sign = function(alg, spHeader, spPayload, key, pass) { 218 var ns1 = KJUR.jws.JWS; 219 var sHeader, pHeader, sPayload; 220 221 // 1. check signatureInput(Header, Payload) is string or object 222 if (typeof spHeader != 'string' && typeof spHeader != 'object') 223 throw "spHeader must be JSON string or object: " + spHeader; 224 225 if (typeof spHeader == 'object') { 226 pHeader = spHeader; 227 sHeader = JSON.stringify(pHeader); 228 } 229 230 if (typeof spHeader == 'string') { 231 sHeader = spHeader; 232 if (! ns1.isSafeJSONString(sHeader)) 233 throw "JWS Head is not safe JSON string: " + sHeader; 234 pHeader = ns1.readSafeJSONString(sHeader); 235 236 } 237 238 sPayload = spPayload; 239 if (typeof spPayload == 'object') sPayload = JSON.stringify(spPayload); 240 241 // 2. use alg if defined in sHeader 242 if ((alg == '' || alg == null) && 243 pHeader['alg'] !== undefined) { 244 alg = pHeader['alg']; 245 } 246 247 // 3. update sHeader to add alg if alg undefined 248 if ((alg != '' && alg != null) && 249 pHeader['alg'] === undefined) { 250 pHeader['alg'] = alg; 251 sHeader = JSON.stringify(pHeader); 252 } 253 254 // 4. check explicit algorithm doesn't match with JWS header. 255 if (alg !== pHeader.alg) 256 throw "alg and sHeader.alg doesn't match: " + alg + "!=" + pHeader.alg; 257 258 // 5. set signature algorithm like SHA1withRSA 259 var sigAlg = null; 260 if (ns1.jwsalg2sigalg[alg] === undefined) { 261 throw "unsupported alg name: " + alg; 262 } else { 263 sigAlg = ns1.jwsalg2sigalg[alg]; 264 } 265 266 var uHeader = utf8tob64u(sHeader); 267 var uPayload = utf8tob64u(sPayload); 268 var uSignatureInput = uHeader + "." + uPayload 269 // 6. sign 270 var hSig = ""; 271 if (sigAlg.substr(0, 4) == "Hmac") { 272 if (key === undefined) 273 throw "mac key shall be specified for HS* alg"; 274 //alert("sigAlg=" + sigAlg); 275 var mac = new KJUR.crypto.Mac({'alg': sigAlg, 'prov': 'cryptojs', 'pass': key}); 276 mac.updateString(uSignatureInput); 277 hSig = mac.doFinal(); 278 } else if (sigAlg.indexOf("withECDSA") != -1) { 279 var sig = new KJUR.crypto.Signature({'alg': sigAlg}); 280 sig.init(key, pass); 281 sig.updateString(uSignatureInput); 282 hASN1Sig = sig.sign(); 283 hSig = KJUR.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig); 284 } else if (sigAlg != "none") { 285 var sig = new KJUR.crypto.Signature({'alg': sigAlg}); 286 sig.init(key, pass); 287 sig.updateString(uSignatureInput); 288 hSig = sig.sign(); 289 } 290 291 var uSig = hextob64u(hSig); 292 return uSignatureInput + "." + uSig; 293 }; 294 295 /** 296 * verify JWS signature by specified key or certificate<br/> 297 * @name verify 298 * @memberOf KJUR.jws.JWS 299 * @function 300 * @static 301 * @param {String} sJWS string of JWS signature to verify 302 * @param {Object} key string of public key, certificate or key object to verify 303 * @param {String} acceptAlgs array of algorithm name strings (OPTION) 304 * @return {Boolean} true if the signature is valid otherwise false 305 * @since jws 3.0.0 306 * @see <a href="http://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Signature.html">jsrsasign KJUR.crypto.Signature method</a> 307 * @see <a href="http://kjur.github.io/jsrsasign/api/symbols/KJUR.crypto.Mac.html">jsrsasign KJUR.crypto.Mac method</a> 308 * @description 309 * <p> 310 * This method verifies a JSON Web Signature Compact Serialization string by the validation 311 * algorithm as described in 312 * <a href="http://self-issued.info/docs/draft-jones-json-web-signature-04.html#anchor5"> 313 * the section 5 of Internet Draft draft-jones-json-web-signature-04.</a> 314 * </p> 315 * <p> 316 * Since 3.2.0 strict key checking has been provided against a JWS algorithm 317 * in a JWS header. 318 * <ul> 319 * <li>In case 'alg' is 'HS*' in the JWS header, 320 * 'key' shall be hexadecimal string for Hmac{256,384,512} shared secret key. 321 * Otherwise it raise an error.</li> 322 * <li>In case 'alg' is 'RS*' or 'PS*' in the JWS header, 323 * 'key' shall be a RSAKey object or a PEM string of 324 * X.509 RSA public key certificate or PKCS#8 RSA public key. 325 * Otherwise it raise an error.</li> 326 * <li>In case 'alg' is 'ES*' in the JWS header, 327 * 'key' shall be a KJUR.crypto.ECDSA object or a PEM string of 328 * X.509 ECC public key certificate or PKCS#8 ECC public key. 329 * Otherwise it raise an error.</li> 330 * <li>In case 'alg' is 'none' in the JWS header, 331 * validation not supported after jsjws 3.1.0.</li> 332 * </ul> 333 * </p> 334 * <p> 335 * NOTE1: The argument 'acceptAlgs' is supported since 3.2.0. 336 * Strongly recommended to provide acceptAlgs to mitigate 337 * signature replacement attacks.<br/> 338 * </p> 339 * <p> 340 * NOTE2: From jsrsasign 4.9.0 jws 3.2.5, Way to provide password 341 * for HS* algorithm is changed. The 'key' attribute value is 342 * passed to {@link KJUR.crypto.Mac.setPassword} so please see 343 * {@link KJUR.crypto.Mac.setPassword} for detail. 344 * As for backword compatibility, if key is a string, has even length and 345 * 0..9, A-F or a-f characters, key string is treated as a hexadecimal 346 * otherwise it is treated as a raw string. 347 * </p> 348 * @example 349 * // 1) verify a RS256 JWS signature by a certificate string. 350 * isValid = KJUR.jws.JWS.verify('eyJh...', '-----BEGIN...', ['RS256']); 351 * 352 * // 2) verify a HS256 JWS signature by a certificate string. 353 * isValid = KJUR.jws.JWS.verify('eyJh...', {hex: '6f62ad...'}, ['HS256']); 354 * isValid = KJUR.jws.JWS.verify('eyJh...', {b64: 'Mi/ab8...a=='}, ['HS256']); 355 * isValid = KJUR.jws.JWS.verify('eyJh...', {utf8: 'Secret秘密'}, ['HS256']); 356 * isValid = KJUR.jws.JWS.verify('eyJh...', '6f62ad', ['HS256']); // implicit hex 357 * isValid = KJUR.jws.JWS.verify('eyJh...', '6f62ada', ['HS256']); // implicit raw string 358 * 359 * // 3) verify a ES256 JWS signature by a KJUR.crypto.ECDSA key object. 360 * var pubkey = KEYUTIL.getKey('-----BEGIN CERT...'); 361 * var isValid = KJUR.jws.JWS.verify('eyJh...', pubkey); 362 */ 363 KJUR.jws.JWS.verify = function(sJWS, key, acceptAlgs) { 364 var jws = KJUR.jws.JWS; 365 var a = sJWS.split("."); 366 var uHeader = a[0]; 367 var uPayload = a[1]; 368 var uSignatureInput = uHeader + "." + uPayload; 369 var hSig = b64utohex(a[2]); 370 371 // 1. parse JWS header 372 var pHeader = jws.readSafeJSONString(b64utoutf8(a[0])); 373 var alg = null; 374 var algType = null; // HS|RS|PS|ES|no 375 if (pHeader.alg === undefined) { 376 throw "algorithm not specified in header"; 377 } else { 378 alg = pHeader.alg; 379 algType = alg.substr(0, 2); 380 } 381 382 // 2. check whether alg is acceptable algorithms 383 if (acceptAlgs != null && 384 Object.prototype.toString.call(acceptAlgs) === '[object Array]' && 385 acceptAlgs.length > 0) { 386 var acceptAlgStr = ":" + acceptAlgs.join(":") + ":"; 387 if (acceptAlgStr.indexOf(":" + alg + ":") == -1) { 388 throw "algorithm '" + alg + "' not accepted in the list"; 389 } 390 } 391 392 // 3. check whether key is a proper key for alg. 393 if (alg != "none" && key === null) { 394 throw "key shall be specified to verify."; 395 } 396 397 // 3.1. There is no key check for HS* because Mac will check it. 398 // since jsrsasign 5.0.0. 399 400 // 3.2. convert key object if key is a public key or cert PEM string 401 if (typeof key == "string" && 402 key.indexOf("-----BEGIN ") != -1) { 403 key = KEYUTIL.getKey(key); 404 } 405 406 // 3.3. check whether key is RSAKey obj if alg is RS* or PS*. 407 if (algType == "RS" || algType == "PS") { 408 if (!(key instanceof RSAKey)) { 409 throw "key shall be a RSAKey obj for RS* and PS* algs"; 410 } 411 } 412 413 // 3.4. check whether key is ECDSA obj if alg is ES*. 414 if (algType == "ES") { 415 if (!(key instanceof KJUR.crypto.ECDSA)) { 416 throw "key shall be a ECDSA obj for ES* algs"; 417 } 418 } 419 420 // 3.5. check when alg is 'none' 421 if (alg == "none") { 422 } 423 424 // 4. check whether alg is supported alg in jsjws. 425 var sigAlg = null; 426 if (jws.jwsalg2sigalg[pHeader.alg] === undefined) { 427 throw "unsupported alg name: " + alg; 428 } else { 429 sigAlg = jws.jwsalg2sigalg[alg]; 430 } 431 432 // 5. verify 433 if (sigAlg == "none") { 434 throw "not supported"; 435 } else if (sigAlg.substr(0, 4) == "Hmac") { 436 var hSig2 = null; 437 if (key === undefined) 438 throw "hexadecimal key shall be specified for HMAC"; 439 //try { 440 var mac = new KJUR.crypto.Mac({'alg': sigAlg, 'pass': key}); 441 mac.updateString(uSignatureInput); 442 hSig2 = mac.doFinal(); 443 //} catch(ex) {}; 444 return hSig == hSig2; 445 } else if (sigAlg.indexOf("withECDSA") != -1) { 446 var hASN1Sig = null; 447 try { 448 hASN1Sig = KJUR.crypto.ECDSA.concatSigToASN1Sig(hSig); 449 } catch (ex) { 450 return false; 451 } 452 var sig = new KJUR.crypto.Signature({'alg': sigAlg}); 453 sig.init(key) 454 sig.updateString(uSignatureInput); 455 return sig.verify(hASN1Sig); 456 } else { 457 var sig = new KJUR.crypto.Signature({'alg': sigAlg}); 458 sig.init(key) 459 sig.updateString(uSignatureInput); 460 return sig.verify(hSig); 461 } 462 }; 463 464 /** 465 * @name verifyJWT 466 * @memberOf KJUR.jws.JWS 467 * @function 468 * @static 469 * @param {String} sJWT string of JSON Web Token(JWT) to verify 470 * @param {Object} key string of public key, certificate or key object to verify 471 * @param {Array} acceptField associative array of acceptable fields (OPTION) 472 * @return {Boolean} true if the JWT token is valid otherwise false 473 * @since jws 3.2.3 jsrsasign 4.8.0 474 * @description 475 * This method verifies a 476 * <a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a> 477 * JSON Web Token(JWT). 478 * It will verify following: 479 * <ul> 480 * <li>Header.alg 481 * <ul> 482 * <li>alg is specified in JWT header.</li> 483 * <li>alg is included in acceptField.alg array. (MANDATORY)</li> 484 * <li>alg is proper for key.</li> 485 * </ul> 486 * </li> 487 * <li>Payload.iss (issuer) - Payload.iss is included in acceptField.iss array if specified. (OPTION)</li> 488 * <li>Payload.sub (subject) - Payload.sub is included in acceptField.sub array if specified. (OPTION)</li> 489 * <li>Payload.aud (audience) - Payload.aud is included in acceptField.aud array or 490 * the same as value if specified. (OPTION)</li> 491 * <li>Time validity 492 * <ul> 493 * <li>If acceptField.verifyAt as number of UNIX origin time is specifed for validation time, 494 * this method will verify at the time for it, otherwise current time will be used to verify.</li> 495 * <li>Payload.exp (expire) - Validation time is smaller than Payloead.exp.</li> 496 * <li>Payload.nbf (not before) - Validation time is greater than Payloead.nbf.</li> 497 * <li>Payload.iat (issued at) - Validation time is greater than Payloead.iat.</li> 498 * </ul> 499 * </li> 500 * <li>Payload.jti (JWT id) - Payload.jti is included in acceptField.jti if specified. (OPTION)</li> 501 * <li>JWS signature of JWS is valid for specified key.</li> 502 * </ul> 503 * 504 * @example 505 * // simple validation for HS256 506 * isValid = KJUR.jws.JWS.verifyJWT("eyJhbG...", "616161", {alg: ["HS256"]}), 507 * 508 * // full validation for RS or PS 509 * pubkey = KEYUTIL.getKey('-----BEGIN CERT...'); 510 * isValid = KJUR.jws.JWS.verifyJWT('eyJh...', pubkey, { 511 * alg: ['RS256', 'RS512', 'PS256', 'PS512'], 512 * iss: ['http://foo.com'], 513 * sub: ['mailto:john@foo.com', 'mailto:alice@foo.com'], 514 * verifyAt: KJUR.jws.IntDate.get('20150520235959Z'), 515 * aud: ['http://foo.com'], // aud: 'http://foo.com' is fine too. 516 * jti: 'id123456' 517 * }); 518 */ 519 KJUR.jws.JWS.verifyJWT = function(sJWT, key, acceptField) { 520 var ns1 = KJUR.jws.JWS; 521 522 // 1. parse JWT 523 var a = sJWT.split("."); 524 var uHeader = a[0]; 525 var uPayload = a[1]; 526 var uSignatureInput = uHeader + "." + uPayload; 527 var hSig = b64utohex(a[2]); 528 529 // 2. parse JWS header 530 var pHeader = ns1.readSafeJSONString(b64utoutf8(uHeader)); 531 532 // 3. parse JWS payload 533 var pPayload = ns1.readSafeJSONString(b64utoutf8(uPayload)); 534 535 // 4. algorithm ('alg' in header) check 536 if (pHeader.alg === undefined) return false; 537 if (acceptField.alg === undefined) 538 throw "acceptField.alg shall be specified"; 539 if (! ns1.inArray(pHeader.alg, acceptField.alg)) return false; 540 541 // 5. issuer ('iss' in payload) check 542 if (pPayload.iss !== undefined && typeof acceptField.iss === "object") { 543 if (! ns1.inArray(pPayload.iss, acceptField.iss)) return false; 544 } 545 546 // 6. subject ('sub' in payload) check 547 if (pPayload.sub !== undefined && typeof acceptField.sub === "object") { 548 if (! ns1.inArray(pPayload.sub, acceptField.sub)) return false; 549 } 550 551 // 7. audience ('aud' in payload) check 552 if (pPayload.aud !== undefined && typeof acceptField.aud === "object") { 553 if (typeof pPayload.aud == "string") { 554 if (! ns1.inArray(pPayload.aud, acceptField.aud)) 555 return false; 556 } else if (typeof pPayload.aud == "object") { 557 if (! ns1.includedArray(pPayload.aud, acceptField.aud)) 558 return false; 559 } 560 } 561 562 // 8. time validity (nbf < now < exp) && (iat <= now) 563 var now = KJUR.jws.IntDate.getNow(); 564 if (acceptField.verifyAt !== undefined && typeof acceptField.verifyAt == "number") { 565 now = acceptField.verifyAt; 566 } 567 568 // 8.1 expired time 'exp' check 569 if (pPayload.exp !== undefined && typeof pPayload.exp == "number") { 570 if (pPayload.exp < now) return false; 571 } 572 573 // 8.2 not before time 'nbf' check 574 if (pPayload.nbf !== undefined && typeof pPayload.nbf == "number") { 575 if (now < pPayload.nbf) return false; 576 } 577 578 // 8.3 issued at time 'iat' check 579 if (pPayload.iat !== undefined && typeof pPayload.iat == "number") { 580 if (now < pPayload.iat) return false; 581 } 582 583 // 9 JWT id 'jti' check 584 if (pPayload.jti !== undefined && acceptField.jti !== undefined) { 585 if (pPayload.jti !== acceptField.jti) return false; 586 } 587 588 // 10 JWS signature check 589 if (! KJUR.jws.JWS.verify(sJWT, key, acceptField.alg)) return false; 590 591 // 11 passed all check 592 return true; 593 }; 594 595 /** 596 * check whether array is included by another array 597 * @name includedArray 598 * @memberOf KJUR.jws.JWS 599 * @function 600 * @static 601 * @param {Array} a1 check whether set a1 is included by a2 602 * @param {Array} a2 check whether set a1 is included by a2 603 * @return {Boolean} check whether set a1 is included by a2 604 * @since jws 3.2.3 605 * This method verifies whether an array is included by another array. 606 * It doesn't care about item ordering in a array. 607 * @example 608 * KJUR.jws.JWS.includedArray(['b'], ['b', 'c', 'a']) => true 609 * KJUR.jws.JWS.includedArray(['a', 'b'], ['b', 'c', 'a']) => true 610 * KJUR.jws.JWS.includedArray(['a', 'b'], ['b', 'c']) => false 611 */ 612 KJUR.jws.JWS.includedArray = function(a1, a2) { 613 var inArray = KJUR.jws.JWS.inArray; 614 if (a1 === null) return false; 615 if (typeof a1 !== "object") return false; 616 if (typeof a1.length !== "number") return false; 617 618 for (var i = 0; i < a1.length; i++) { 619 if (! inArray(a1[i], a2)) return false; 620 } 621 return true; 622 }; 623 624 /** 625 * check whether item is included by array 626 * @name inArray 627 * @memberOf KJUR.jws.JWS 628 * @function 629 * @static 630 * @param {String} item check whether item is included by array 631 * @param {Array} a check whether item is included by array 632 * @return {Boolean} check whether item is included by array 633 * @since jws 3.2.3 634 * This method verifies whether an item is included by an array. 635 * It doesn't care about item ordering in an array. 636 * @example 637 * KJUR.jws.JWS.inArray('b', ['b', 'c', 'a']) => true 638 * KJUR.jws.JWS.inArray('a', ['b', 'c', 'a']) => true 639 * KJUR.jws.JWS.inArray('a', ['b', 'c']) => false 640 */ 641 KJUR.jws.JWS.inArray = function(item, a) { 642 if (a === null) return false; 643 if (typeof a !== "object") return false; 644 if (typeof a.length !== "number") return false; 645 for (var i = 0; i < a.length; i++) { 646 if (a[i] == item) return true; 647 } 648 return false; 649 }; 650 651 /** 652 * static associative array of general signature algorithm name from JWS algorithm name 653 * @since jws 3.0.0 654 */ 655 KJUR.jws.JWS.jwsalg2sigalg = { 656 "HS256": "HmacSHA256", 657 "HS384": "HmacSHA384", 658 "HS512": "HmacSHA512", 659 "RS256": "SHA256withRSA", 660 "RS384": "SHA384withRSA", 661 "RS512": "SHA512withRSA", 662 "ES256": "SHA256withECDSA", 663 "ES384": "SHA384withECDSA", 664 //"ES512": "SHA512withECDSA", // unsupported because of jsrsasign's bug 665 "PS256": "SHA256withRSAandMGF1", 666 "PS384": "SHA384withRSAandMGF1", 667 "PS512": "SHA512withRSAandMGF1", 668 "none": "none", 669 }; 670 671 // === utility static method ====================================================== 672 673 /** 674 * check whether a String "s" is a safe JSON string or not.<br/> 675 * If a String "s" is a malformed JSON string or an other object type 676 * this returns 0, otherwise this returns 1. 677 * @name isSafeJSONString 678 * @memberOf KJUR.jws.JWS 679 * @function 680 * @static 681 * @param {String} s JSON string 682 * @return {Number} 1 or 0 683 */ 684 KJUR.jws.JWS.isSafeJSONString = function(s, h, p) { 685 var o = null; 686 try { 687 o = jsonParse(s); 688 if (typeof o != "object") return 0; 689 if (o.constructor === Array) return 0; 690 if (h) h[p] = o; 691 return 1; 692 } catch (ex) { 693 return 0; 694 } 695 }; 696 697 /** 698 * read a String "s" as JSON object if it is safe.<br/> 699 * If a String "s" is a malformed JSON string or not JSON string, 700 * this returns null, otherwise returns JSON object. 701 * @name readSafeJSONString 702 * @memberOf KJUR.jws.JWS 703 * @function 704 * @static 705 * @param {String} s JSON string 706 * @return {Object} JSON object or null 707 * @since 1.1.1 708 */ 709 KJUR.jws.JWS.readSafeJSONString = function(s) { 710 var o = null; 711 try { 712 o = jsonParse(s); 713 if (typeof o != "object") return null; 714 if (o.constructor === Array) return null; 715 return o; 716 } catch (ex) { 717 return null; 718 } 719 }; 720 721 /** 722 * get Encoed Signature Value from JWS string.<br/> 723 * @name getEncodedSignatureValueFromJWS 724 * @memberOf KJUR.jws.JWS 725 * @function 726 * @static 727 * @param {String} sJWS JWS signature string to be verified 728 * @return {String} string of Encoded Signature Value 729 * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". 730 */ 731 KJUR.jws.JWS.getEncodedSignatureValueFromJWS = function(sJWS) { 732 if (sJWS.match(/^[^.]+\.[^.]+\.([^.]+)$/) == null) { 733 throw "JWS signature is not a form of 'Head.Payload.SigValue'."; 734 } 735 return RegExp.$1; 736 }; 737 738 /** 739 * IntDate class for time representation for JSON Web Token(JWT) 740 * @class KJUR.jws.IntDate class 741 * @name KJUR.jws.IntDate 742 * @since jws 3.0.1 743 * @description 744 * Utility class for IntDate which is integer representation of UNIX origin time 745 * used in JSON Web Token(JWT). 746 */ 747 KJUR.jws.IntDate = {}; 748 749 /** 750 * get UNIX origin time from by string 751 * @name get 752 * @memberOf KJUR.jws.IntDate 753 * @function 754 * @static 755 * @param {String} s string of time representation 756 * @return {Integer} UNIX origin time in seconds for argument 's' 757 * @since jws 3.0.1 758 * @throws "unsupported format: s" when malformed format 759 * @description 760 * This method will accept following representation of time. 761 * <ul> 762 * <li>now - current time</li> 763 * <li>now + 1hour - after 1 hour from now</li> 764 * <li>now + 1day - after 1 day from now</li> 765 * <li>now + 1month - after 30 days from now</li> 766 * <li>now + 1year - after 365 days from now</li> 767 * <li>YYYYmmDDHHMMSSZ - UTC time (ex. 20130828235959Z)</li> 768 * <li>number - UNIX origin time (seconds from 1970-01-01 00:00:00) (ex. 1377714748)</li> 769 * </ul> 770 */ 771 KJUR.jws.IntDate.get = function(s) { 772 if (s == "now") { 773 return KJUR.jws.IntDate.getNow(); 774 } else if (s == "now + 1hour") { 775 return KJUR.jws.IntDate.getNow() + 60 * 60; 776 } else if (s == "now + 1day") { 777 return KJUR.jws.IntDate.getNow() + 60 * 60 * 24; 778 } else if (s == "now + 1month") { 779 return KJUR.jws.IntDate.getNow() + 60 * 60 * 24 * 30; 780 } else if (s == "now + 1year") { 781 return KJUR.jws.IntDate.getNow() + 60 * 60 * 24 * 365; 782 } else if (s.match(/Z$/)) { 783 return KJUR.jws.IntDate.getZulu(s); 784 } else if (s.match(/^[0-9]+$/)) { 785 return parseInt(s); 786 } 787 throw "unsupported format: " + s; 788 }; 789 790 /** 791 * get UNIX origin time from Zulu time representation string 792 * @name getZulu 793 * @memberOf KJUR.jws.IntDate 794 * @function 795 * @static 796 * @param {String} s string of Zulu time representation (ex. 20151012125959Z) 797 * @return {Integer} UNIX origin time in seconds for argument 's' 798 * @since jws 3.0.1 799 * @throws "unsupported format: s" when malformed format 800 * @description 801 * This method provides UNIX origin time from Zulu time. 802 * @example 803 * KJUR.jws.IntDate.getZulu("20151012125959Z") => 1478... 804 */ 805 KJUR.jws.IntDate.getZulu = function(s) { 806 if (a = s.match(/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z/)) { 807 var year = parseInt(RegExp.$1); 808 var month = parseInt(RegExp.$2) - 1; 809 var day = parseInt(RegExp.$3); 810 var hour = parseInt(RegExp.$4); 811 var min = parseInt(RegExp.$5); 812 var sec = parseInt(RegExp.$6); 813 var d = new Date(Date.UTC(year, month, day, hour, min, sec)); 814 return ~~(d / 1000); 815 } 816 throw "unsupported format: " + s; 817 }; 818 819 /** 820 * get UNIX origin time of current time 821 * @name getNow 822 * @memberOf KJUR.jws.IntDate 823 * @function 824 * @static 825 * @return {Integer} UNIX origin time for current time 826 * @since jws 3.0.1 827 * @description 828 * This method provides UNIX origin time for current time 829 * @example 830 * KJUR.jws.IntDate.getNow() => 1478... 831 */ 832 KJUR.jws.IntDate.getNow = function() { 833 var d = ~~(new Date() / 1000); 834 return d; 835 }; 836 837 /** 838 * get UTC time string from UNIX origin time value 839 * @name intDate2UTCString 840 * @memberOf KJUR.jws.IntDate 841 * @function 842 * @static 843 * @param {Integer} intDate UNIX origin time value (ex. 1478...) 844 * @return {String} UTC time string 845 * @since jws 3.0.1 846 * @description 847 * This method provides UTC time string for UNIX origin time value. 848 * @example 849 * KJUR.jws.IntDate.intDate2UTCString(1478...) => "2015 Oct ..." 850 */ 851 KJUR.jws.IntDate.intDate2UTCString = function(intDate) { 852 var d = new Date(intDate * 1000); 853 return d.toUTCString(); 854 }; 855 856 /** 857 * get UTC time string from UNIX origin time value 858 * @name intDate2Zulu 859 * @memberOf KJUR.jws.IntDate 860 * @function 861 * @static 862 * @param {Integer} intDate UNIX origin time value (ex. 1478...) 863 * @return {String} Zulu time string 864 * @since jws 3.0.1 865 * @description 866 * This method provides Zulu time string for UNIX origin time value. 867 * @example 868 * KJUR.jws.IntDate.intDate2UTCString(1478...) => "20151012...Z" 869 */ 870 KJUR.jws.IntDate.intDate2Zulu = function(intDate) { 871 var d = new Date(intDate * 1000); 872 var year = ("0000" + d.getUTCFullYear()).slice(-4); 873 var mon = ("00" + (d.getUTCMonth() + 1)).slice(-2); 874 var day = ("00" + d.getUTCDate()).slice(-2); 875 var hour = ("00" + d.getUTCHours()).slice(-2); 876 var min = ("00" + d.getUTCMinutes()).slice(-2); 877 var sec = ("00" + d.getUTCSeconds()).slice(-2); 878 return year + mon + day + hour + min + sec + "Z"; 879 }; 880