diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..db7fd048 --- /dev/null +++ b/.babelrc @@ -0,0 +1,4 @@ +{ + "presets": ["es2015"], + "plugins": ["babel-plugin-add-module-exports"] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..e5164bd1 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,48 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Mocha", + "type": "node", + "request": "launch", + "program": "${workspaceRoot}\\node_modules\\mocha\\bin\\_mocha", + "stopOnEntry": false, + "args": ["--compilers", "js:babel-register", "test/*.spec.js"], + "cwd": "${workspaceRoot}", + "preLaunchTask": null, + "runtimeExecutable": null + }, + { + "name": "Launch", + "type": "node", + "request": "launch", + "program": "${workspaceRoot}\\src\\index.js", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceRoot}", + "preLaunchTask": null, + "runtimeExecutable": null, + "runtimeArgs": [ + "--nolazy" + ], + "env": { + "NODE_ENV": "development" + }, + "externalConsole": false, + "sourceMaps": false, + "outDir": null + }, + { + "name": "Attach", + "type": "node", + "request": "attach", + "port": 5858, + "address": "localhost", + "restart": false, + "sourceMaps": false, + "outDir": null, + "localRoot": "${workspaceRoot}", + "remoteRoot": null + } + ] +} \ No newline at end of file diff --git a/bower.json b/bower.json deleted file mode 100644 index 87693587..00000000 --- a/bower.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "oidc-client", - "version": "0.3.3", - "homepage": "https://github.com/IdentityModel/oidc-client", - "authors": [ - "Brock Allen ", - "Dominick Baier " - ], - "description": "OpenID Connect (OIDC) client library", - "main": "dist/oidc-client.js", - "license": "Apache-2.0", - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/dist/oidc-client.js b/dist/oidc-client.js deleted file mode 100644 index 3e442fdd..00000000 --- a/dist/oidc-client.js +++ /dev/null @@ -1,8257 +0,0 @@ -(function () { - - // globals - var _promiseFactory; - var _httpRequest; -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -/** - * CryptoJS core components. - */ -var CryptoJS = CryptoJS || (function (Math, undefined) { - /** - * CryptoJS namespace. - */ - var C = {}; - - /** - * Library namespace. - */ - var C_lib = C.lib = {}; - - /** - * Base object for prototypal inheritance. - */ - var Base = C_lib.Base = (function () { - function F() {} - - return { - /** - * Creates a new object that inherits from this object. - * - * @param {Object} overrides Properties to copy into the new object. - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * field: 'value', - * - * method: function () { - * } - * }); - */ - extend: function (overrides) { - // Spawn - F.prototype = this; - var subtype = new F(); - - // Augment - if (overrides) { - subtype.mixIn(overrides); - } - - // Create default initializer - if (!subtype.hasOwnProperty('init')) { - subtype.init = function () { - subtype.$super.init.apply(this, arguments); - }; - } - - // Initializer's prototype is the subtype object - subtype.init.prototype = subtype; - - // Reference supertype - subtype.$super = this; - - return subtype; - }, - - /** - * Extends this object and runs the init method. - * Arguments to create() will be passed to init(). - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var instance = MyType.create(); - */ - create: function () { - var instance = this.extend(); - instance.init.apply(instance, arguments); - - return instance; - }, - - /** - * Initializes a newly created object. - * Override this method to add some logic when your objects are created. - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * init: function () { - * // ... - * } - * }); - */ - init: function () { - }, - - /** - * Copies properties into this object. - * - * @param {Object} properties The properties to mix in. - * - * @example - * - * MyType.mixIn({ - * field: 'value' - * }); - */ - mixIn: function (properties) { - for (var propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - this[propertyName] = properties[propertyName]; - } - } - - // IE won't copy toString using the loop above - if (properties.hasOwnProperty('toString')) { - this.toString = properties.toString; - } - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = instance.clone(); - */ - clone: function () { - return this.init.prototype.extend(this); - } - }; - }()); - - /** - * An array of 32-bit words. - * - * @property {Array} words The array of 32-bit words. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var WordArray = C_lib.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of 32-bit words. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.create(); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 4; - } - }, - - /** - * Converts this word array to a string. - * - * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex - * - * @return {string} The stringified word array. - * - * @example - * - * var string = wordArray + ''; - * var string = wordArray.toString(); - * var string = wordArray.toString(CryptoJS.enc.Utf8); - */ - toString: function (encoder) { - return (encoder || Hex).stringify(this); - }, - - /** - * Concatenates a word array to this word array. - * - * @param {WordArray} wordArray The word array to append. - * - * @return {WordArray} This word array. - * - * @example - * - * wordArray1.concat(wordArray2); - */ - concat: function (wordArray) { - // Shortcuts - var thisWords = this.words; - var thatWords = wordArray.words; - var thisSigBytes = this.sigBytes; - var thatSigBytes = wordArray.sigBytes; - - // Clamp excess bits - this.clamp(); - - // Concat - if (thisSigBytes % 4) { - // Copy one byte at a time - for (var i = 0; i < thatSigBytes; i++) { - var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else if (thatWords.length > 0xffff) { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } else { - // Copy all words at once - thisWords.push.apply(thisWords, thatWords); - } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; - - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, - - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); - - return clone; - }, - - /** - * Creates a word array filled with random bytes. - * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.random(16); - */ - random: function (nBytes) { - var words = []; - for (var i = 0; i < nBytes; i += 4) { - words.push((Math.random() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); - - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; - - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { - /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static - * - * @example - * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); - }, - - /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); - */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); - } - - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); - } - - return latin1Chars.join(''); - }, - - /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); - */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } - }; - - /** - * UTF-8 encoding strategy. - */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, - - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); - } - }; - - /** - * Abstract buffered block algorithm template. - * - * The property blockSize must be implemented in a concrete subtype. - * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 - */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, - - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); - } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); - } - - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } - - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } - - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); - - return clone; - }, - - _minBufferSize: 0 - }); - - /** - * Abstract hasher template. - * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) - */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, - - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); - - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, - - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } - - // Perform concrete-hasher logic - var hash = this._doFinalize(); - - return hash; - }, - - blockSize: 512/32, - - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, - - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; - } - }); - - /** - * Algorithm namespace. - */ - var C_algo = C.algo = {}; - - return C; -}(Math)); - -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Reusable object - var W = []; - - /** - * SHA-1 hash algorithm. - */ - var SHA1 = C_algo.SHA1 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476, - 0xc3d2e1f0 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Shortcut - var H = this._hash.words; - - // Working variables - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - // Computation - for (var i = 0; i < 80; i++) { - if (i < 16) { - W[i] = M[offset + i] | 0; - } else { - var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = (n << 1) | (n >>> 31); - } - - var t = ((a << 5) | (a >>> 27)) + e + W[i]; - if (i < 20) { - t += ((b & c) | (~b & d)) + 0x5a827999; - } else if (i < 40) { - t += (b ^ c ^ d) + 0x6ed9eba1; - } else if (i < 60) { - t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; - } else /* if (i < 80) */ { - t += (b ^ c ^ d) - 0x359d3e2a; - } - - e = d; - d = c; - c = (b << 30) | (b >>> 2); - b = a; - a = t; - } - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - H[4] = (H[4] + e) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; - data.sigBytes = dataWords.length * 4; - - // Hash final blocks - this._process(); - - // Return final computed hash - return this._hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.SHA1('message'); - * var hash = CryptoJS.SHA1(wordArray); - */ - C.SHA1 = Hasher._createHelper(SHA1); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacSHA1(message, key); - */ - C.HmacSHA1 = Hasher._createHmacHelper(SHA1); -}()); - -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Initialization and round constants tables - var H = []; - var K = []; - - // Compute constants - (function () { - function isPrime(n) { - var sqrtN = Math.sqrt(n); - for (var factor = 2; factor <= sqrtN; factor++) { - if (!(n % factor)) { - return false; - } - } - - return true; - } - - function getFractionalBits(n) { - return ((n - (n | 0)) * 0x100000000) | 0; - } - - var n = 2; - var nPrime = 0; - while (nPrime < 64) { - if (isPrime(n)) { - if (nPrime < 8) { - H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); - } - K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); - - nPrime++; - } - - n++; - } - }()); - - // Reusable object - var W = []; - - /** - * SHA-256 hash algorithm. - */ - var SHA256 = C_algo.SHA256 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init(H.slice(0)); - }, - - _doProcessBlock: function (M, offset) { - // Shortcut - var H = this._hash.words; - - // Working variables - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - var f = H[5]; - var g = H[6]; - var h = H[7]; - - // Computation - for (var i = 0; i < 64; i++) { - if (i < 16) { - W[i] = M[offset + i] | 0; - } else { - var gamma0x = W[i - 15]; - var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ - ((gamma0x << 14) | (gamma0x >>> 18)) ^ - (gamma0x >>> 3); - - var gamma1x = W[i - 2]; - var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ - ((gamma1x << 13) | (gamma1x >>> 19)) ^ - (gamma1x >>> 10); - - W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; - } - - var ch = (e & f) ^ (~e & g); - var maj = (a & b) ^ (a & c) ^ (b & c); - - var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); - var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); - - var t1 = h + sigma1 + ch + K[i] + W[i]; - var t2 = sigma0 + maj; - - h = g; - g = f; - f = e; - e = (d + t1) | 0; - d = c; - c = b; - b = a; - a = (t1 + t2) | 0; - } - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - H[4] = (H[4] + e) | 0; - H[5] = (H[5] + f) | 0; - H[6] = (H[6] + g) | 0; - H[7] = (H[7] + h) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; - data.sigBytes = dataWords.length * 4; - - // Hash final blocks - this._process(); - - // Return final computed hash - return this._hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.SHA256('message'); - * var hash = CryptoJS.SHA256(wordArray); - */ - C.SHA256 = Hasher._createHelper(SHA256); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacSHA256(message, key); - */ - C.HmacSHA256 = Hasher._createHmacHelper(SHA256); -}(Math)); - -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function (undefined) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var Base = C_lib.Base; - var X32WordArray = C_lib.WordArray; - - /** - * x64 namespace. - */ - var C_x64 = C.x64 = {}; - - /** - * A 64-bit word. - */ - var X64Word = C_x64.Word = Base.extend({ - /** - * Initializes a newly created 64-bit word. - * - * @param {number} high The high 32 bits. - * @param {number} low The low 32 bits. - * - * @example - * - * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); - */ - init: function (high, low) { - this.high = high; - this.low = low; - } - - /** - * Bitwise NOTs this word. - * - * @return {X64Word} A new x64-Word object after negating. - * - * @example - * - * var negated = x64Word.not(); - */ - // not: function () { - // var high = ~this.high; - // var low = ~this.low; - - // return X64Word.create(high, low); - // }, - - /** - * Bitwise ANDs this word with the passed word. - * - * @param {X64Word} word The x64-Word to AND with this word. - * - * @return {X64Word} A new x64-Word object after ANDing. - * - * @example - * - * var anded = x64Word.and(anotherX64Word); - */ - // and: function (word) { - // var high = this.high & word.high; - // var low = this.low & word.low; - - // return X64Word.create(high, low); - // }, - - /** - * Bitwise ORs this word with the passed word. - * - * @param {X64Word} word The x64-Word to OR with this word. - * - * @return {X64Word} A new x64-Word object after ORing. - * - * @example - * - * var ored = x64Word.or(anotherX64Word); - */ - // or: function (word) { - // var high = this.high | word.high; - // var low = this.low | word.low; - - // return X64Word.create(high, low); - // }, - - /** - * Bitwise XORs this word with the passed word. - * - * @param {X64Word} word The x64-Word to XOR with this word. - * - * @return {X64Word} A new x64-Word object after XORing. - * - * @example - * - * var xored = x64Word.xor(anotherX64Word); - */ - // xor: function (word) { - // var high = this.high ^ word.high; - // var low = this.low ^ word.low; - - // return X64Word.create(high, low); - // }, - - /** - * Shifts this word n bits to the left. - * - * @param {number} n The number of bits to shift. - * - * @return {X64Word} A new x64-Word object after shifting. - * - * @example - * - * var shifted = x64Word.shiftL(25); - */ - // shiftL: function (n) { - // if (n < 32) { - // var high = (this.high << n) | (this.low >>> (32 - n)); - // var low = this.low << n; - // } else { - // var high = this.low << (n - 32); - // var low = 0; - // } - - // return X64Word.create(high, low); - // }, - - /** - * Shifts this word n bits to the right. - * - * @param {number} n The number of bits to shift. - * - * @return {X64Word} A new x64-Word object after shifting. - * - * @example - * - * var shifted = x64Word.shiftR(7); - */ - // shiftR: function (n) { - // if (n < 32) { - // var low = (this.low >>> n) | (this.high << (32 - n)); - // var high = this.high >>> n; - // } else { - // var low = this.high >>> (n - 32); - // var high = 0; - // } - - // return X64Word.create(high, low); - // }, - - /** - * Rotates this word n bits to the left. - * - * @param {number} n The number of bits to rotate. - * - * @return {X64Word} A new x64-Word object after rotating. - * - * @example - * - * var rotated = x64Word.rotL(25); - */ - // rotL: function (n) { - // return this.shiftL(n).or(this.shiftR(64 - n)); - // }, - - /** - * Rotates this word n bits to the right. - * - * @param {number} n The number of bits to rotate. - * - * @return {X64Word} A new x64-Word object after rotating. - * - * @example - * - * var rotated = x64Word.rotR(7); - */ - // rotR: function (n) { - // return this.shiftR(n).or(this.shiftL(64 - n)); - // }, - - /** - * Adds this word with the passed word. - * - * @param {X64Word} word The x64-Word to add with this word. - * - * @return {X64Word} A new x64-Word object after adding. - * - * @example - * - * var added = x64Word.add(anotherX64Word); - */ - // add: function (word) { - // var low = (this.low + word.low) | 0; - // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; - // var high = (this.high + word.high + carry) | 0; - - // return X64Word.create(high, low); - // } - }); - - /** - * An array of 64-bit words. - * - * @property {Array} words The array of CryptoJS.x64.Word objects. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var X64WordArray = C_x64.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.x64.WordArray.create(); - * - * var wordArray = CryptoJS.x64.WordArray.create([ - * CryptoJS.x64.Word.create(0x00010203, 0x04050607), - * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) - * ]); - * - * var wordArray = CryptoJS.x64.WordArray.create([ - * CryptoJS.x64.Word.create(0x00010203, 0x04050607), - * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) - * ], 10); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 8; - } - }, - - /** - * Converts this 64-bit word array to a 32-bit word array. - * - * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. - * - * @example - * - * var x32WordArray = x64WordArray.toX32(); - */ - toX32: function () { - // Shortcuts - var x64Words = this.words; - var x64WordsLength = x64Words.length; - - // Convert - var x32Words = []; - for (var i = 0; i < x64WordsLength; i++) { - var x64Word = x64Words[i]; - x32Words.push(x64Word.high); - x32Words.push(x64Word.low); - } - - return X32WordArray.create(x32Words, this.sigBytes); - }, - - /** - * Creates a copy of this word array. - * - * @return {X64WordArray} The clone. - * - * @example - * - * var clone = x64WordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - - // Clone "words" array - var words = clone.words = this.words.slice(0); - - // Clone each X64Word object - var wordsLength = words.length; - for (var i = 0; i < wordsLength; i++) { - words[i] = words[i].clone(); - } - - return clone; - } - }); -}()); -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var Hasher = C_lib.Hasher; - var C_x64 = C.x64; - var X64Word = C_x64.Word; - var X64WordArray = C_x64.WordArray; - var C_algo = C.algo; - - function X64Word_create() { - return X64Word.create.apply(X64Word, arguments); - } - - // Constants - var K = [ - X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), - X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), - X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), - X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), - X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), - X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), - X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), - X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), - X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), - X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), - X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), - X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), - X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), - X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), - X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), - X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), - X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), - X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), - X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), - X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), - X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), - X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), - X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), - X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), - X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), - X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), - X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), - X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), - X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), - X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), - X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), - X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), - X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), - X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), - X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), - X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), - X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), - X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), - X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), - X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) - ]; - - // Reusable objects - var W = []; - (function () { - for (var i = 0; i < 80; i++) { - W[i] = X64Word_create(); - } - }()); - - /** - * SHA-512 hash algorithm. - */ - var SHA512 = C_algo.SHA512 = Hasher.extend({ - _doReset: function () { - this._hash = new X64WordArray.init([ - new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), - new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), - new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), - new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) - ]); - }, - - _doProcessBlock: function (M, offset) { - // Shortcuts - var H = this._hash.words; - - var H0 = H[0]; - var H1 = H[1]; - var H2 = H[2]; - var H3 = H[3]; - var H4 = H[4]; - var H5 = H[5]; - var H6 = H[6]; - var H7 = H[7]; - - var H0h = H0.high; - var H0l = H0.low; - var H1h = H1.high; - var H1l = H1.low; - var H2h = H2.high; - var H2l = H2.low; - var H3h = H3.high; - var H3l = H3.low; - var H4h = H4.high; - var H4l = H4.low; - var H5h = H5.high; - var H5l = H5.low; - var H6h = H6.high; - var H6l = H6.low; - var H7h = H7.high; - var H7l = H7.low; - - // Working variables - var ah = H0h; - var al = H0l; - var bh = H1h; - var bl = H1l; - var ch = H2h; - var cl = H2l; - var dh = H3h; - var dl = H3l; - var eh = H4h; - var el = H4l; - var fh = H5h; - var fl = H5l; - var gh = H6h; - var gl = H6l; - var hh = H7h; - var hl = H7l; - - // Rounds - for (var i = 0; i < 80; i++) { - // Shortcut - var Wi = W[i]; - - // Extend message - if (i < 16) { - var Wih = Wi.high = M[offset + i * 2] | 0; - var Wil = Wi.low = M[offset + i * 2 + 1] | 0; - } else { - // Gamma0 - var gamma0x = W[i - 15]; - var gamma0xh = gamma0x.high; - var gamma0xl = gamma0x.low; - var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); - var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); - - // Gamma1 - var gamma1x = W[i - 2]; - var gamma1xh = gamma1x.high; - var gamma1xl = gamma1x.low; - var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); - var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7 = W[i - 7]; - var Wi7h = Wi7.high; - var Wi7l = Wi7.low; - - var Wi16 = W[i - 16]; - var Wi16h = Wi16.high; - var Wi16l = Wi16.low; - - var Wil = gamma0l + Wi7l; - var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); - var Wil = Wil + gamma1l; - var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); - var Wil = Wil + Wi16l; - var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); - - Wi.high = Wih; - Wi.low = Wil; - } - - var chh = (eh & fh) ^ (~eh & gh); - var chl = (el & fl) ^ (~el & gl); - var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); - var majl = (al & bl) ^ (al & cl) ^ (bl & cl); - - var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); - var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); - var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); - var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); - - // t1 = h + sigma1 + ch + K[i] + W[i] - var Ki = K[i]; - var Kih = Ki.high; - var Kil = Ki.low; - - var t1l = hl + sigma1l; - var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); - var t1l = t1l + chl; - var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); - var t1l = t1l + Kil; - var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); - var t1l = t1l + Wil; - var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); - - // t2 = sigma0 + maj - var t2l = sigma0l + majl; - var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); - - // Update working variables - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; - } - - // Intermediate hash value - H0l = H0.low = (H0l + al); - H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); - H1l = H1.low = (H1l + bl); - H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); - H2l = H2.low = (H2l + cl); - H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); - H3l = H3.low = (H3l + dl); - H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); - H4l = H4.low = (H4l + el); - H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); - H5l = H5.low = (H5l + fl); - H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); - H6l = H6.low = (H6l + gl); - H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); - H7l = H7.low = (H7l + hl); - H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; - data.sigBytes = dataWords.length * 4; - - // Hash final blocks - this._process(); - - // Convert hash to 32-bit word array before returning - var hash = this._hash.toX32(); - - // Return final computed hash - return hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - }, - - blockSize: 1024/32 - }); - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.SHA512('message'); - * var hash = CryptoJS.SHA512(wordArray); - */ - C.SHA512 = Hasher._createHelper(SHA512); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacSHA512(message, key); - */ - C.HmacSHA512 = Hasher._createHmacHelper(SHA512); -}()); - - -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var b64pad="="; - -function hex2b64(h) { - var i; - var c; - var ret = ""; - for(i = 0; i+3 <= h.length; i+=3) { - c = parseInt(h.substring(i,i+3),16); - ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); - } - if(i+1 == h.length) { - c = parseInt(h.substring(i,i+1),16); - ret += b64map.charAt(c << 2); - } - else if(i+2 == h.length) { - c = parseInt(h.substring(i,i+2),16); - ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); - } - if (b64pad) while((ret.length & 3) > 0) ret += b64pad; - return ret; -} - -// convert a base64 string to hex -function b64tohex(s) { - var ret = "" - var i; - var k = 0; // b64 state, 0-3 - var slop; - var v; - for(i = 0; i < s.length; ++i) { - if(s.charAt(i) == b64pad) break; - v = b64map.indexOf(s.charAt(i)); - if(v < 0) continue; - if(k == 0) { - ret += int2char(v >> 2); - slop = v & 3; - k = 1; - } - else if(k == 1) { - ret += int2char((slop << 2) | (v >> 4)); - slop = v & 0xf; - k = 2; - } - else if(k == 2) { - ret += int2char(slop); - ret += int2char(v >> 2); - slop = v & 3; - k = 3; - } - else { - ret += int2char((slop << 2) | (v >> 4)); - ret += int2char(v & 0xf); - k = 0; - } - } - if(k == 1) - ret += int2char(slop << 2); - return ret; -} - -// convert a base64 string to a byte/number array -function b64toBA(s) { - //piggyback on b64tohex for now, optimize later - var h = b64tohex(s); - var i; - var a = new Array(); - for(i = 0; 2*i < h.length; ++i) { - a[i] = parseInt(h.substring(2*i,2*i+2),16); - } - return a; -} -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Copyright (c) 2005 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. - -// Basic JavaScript BN library - subset useful for RSA encryption. - -// Bits per digit -var dbits; - -// JavaScript engine analysis -var canary = 0xdeadbeefcafe; -var j_lm = ((canary&0xffffff)==0xefcafe); - -// (public) Constructor -function BigInteger(a,b,c) { - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); -} - -// return new, unset BigInteger -function nbi() { return new BigInteger(null); } - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this[i++]+w[j]+c; - c = Math.floor(v/0x4000000); - w[j++] = v&0x3ffffff; - } - return c; -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i,x,w,j,c,n) { - var xl = x&0x7fff, xh = x>>15; - while(--n >= 0) { - var l = this[i]&0x7fff; - var h = this[i++]>>15; - var m = xh*l+h*xl; - l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); - c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); - w[j++] = l&0x3fffffff; - } - return c; -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i,x,w,j,c,n) { - var xl = x&0x3fff, xh = x>>14; - while(--n >= 0) { - var l = this[i]&0x3fff; - var h = this[i++]>>14; - var m = xh*l+h*xl; - l = xl*l+((m&0x3fff)<<14)+w[j]+c; - c = (l>>28)+(m>>14)+xh*h; - w[j++] = l&0xfffffff; - } - return c; -} -if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; -} -else if(j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; -} -else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; -} - -BigInteger.prototype.DB = dbits; -BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; -} - -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1; - this.s = (x<0)?-1:0; - if(x > 0) this[0] = x; - else if(x < -1) this[0] = x+this.DV; - else this.t = 0; -} - -// return bigint initialized to value -function nbv(i) { var r = nbi(); r.fromInt(i); return r; } - -// (protected) set from string and radix -function bnpFromString(s,b) { - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 256) k = 8; // byte array - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else { this.fromRadix(s,b); return; } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while(--i >= 0) { - var x = (k==8)?s[i]&0xff:intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if(sh == 0) - this[this.t++] = x; - else if(sh+k > this.DB) { - this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); - } - else - this[this.t-1] |= x<= this.DB) sh -= this.DB; - } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; -} - -// (public) return string representation in given radix -function bnToString(b) { - if(this.s < 0) return "-"+this.negate().toString(b); - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else return this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this[i]&((1<>(p+=this.DB-k); - } - else { - d = (this[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } - } - if(d > 0) m = true; - if(m) r += int2char(d); - } - } - return m?r:"0"; -} - -// (public) -this -function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - -// (public) |this| -function bnAbs() { return (this.s<0)?this.negate():this; } - -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s-a.s; - if(r != 0) return r; - var i = this.t; - r = i-a.t; - if(r != 0) return (this.s<0)?-r:r; - while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; - return 0; -} - -// returns bit length of the integer x -function nbits(x) { - var r = 1, t; - if((t=x>>>16) != 0) { x = t; r += 16; } - if((t=x>>8) != 0) { x = t; r += 8; } - if((t=x>>4) != 0) { x = t; r += 4; } - if((t=x>>2) != 0) { x = t; r += 2; } - if((t=x>>1) != 0) { x = t; r += 1; } - return r; -} - -// (public) return the number of bits in "this" -function bnBitLength() { - if(this.t <= 0) return 0; - return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); -} - -// (protected) r = this << n*DB -function bnpDLShiftTo(n,r) { - var i; - for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; - for(i = n-1; i >= 0; --i) r[i] = 0; - r.t = this.t+n; - r.s = this.s; -} - -// (protected) r = this >> n*DB -function bnpDRShiftTo(n,r) { - for(var i = n; i < this.t; ++i) r[i-n] = this[i]; - r.t = Math.max(this.t-n,0); - r.s = this.s; -} - -// (protected) r = this << n -function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r[i+ds+1] = (this[i]>>cbs)|c; - c = (this[i]&bm)<= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); -} - -// (protected) r = this >> n -function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r[i-ds-1] |= (this[i]&bm)<>bs; - } - if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c -= a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r[i++] = this.DV+c; - else if(c > 0) r[i++] = c; - r.t = i; - r.clamp(); -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a,r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i+y.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); - r.s = 0; - r.clamp(); - if(this.s != a.s) BigInteger.ZERO.subTo(r,r); -} - -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2*x.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < x.t-1; ++i) { - var c = x.am(i,x[i],r,2*i,0,1); - if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { - r[i+x.t] -= x.DV; - r[i+x.t+1] = 1; - } - } - if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); - r.s = 0; - r.clamp(); -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m,q,r) { - var pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus - if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } - else { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y[ys-1]; - if(y0 == 0) return; - var yt = y0*(1<1)?y[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 0) { - r[r.t++] = 1; - r.subTo(t,r); - } - BigInteger.ONE.dlShiftTo(ys,t); - t.subTo(y,y); // "negative" y so we can replace sub with am later - while(y.t < ys) y[y.t++] = 0; - while(--j >= 0) { - // Estimate quotient digit - var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); - if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out - y.dlShiftTo(j,t); - r.subTo(t,r); - while(r[i] < --qd) r.subTo(t,r); - } - } - if(q != null) { - r.drShiftTo(ys,q); - if(ts != ms) BigInteger.ZERO.subTo(q,q); - } - r.t = ys; - r.clamp(); - if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder - if(ts < 0) BigInteger.ZERO.subTo(r,r); -} - -// (public) this mod a -function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); - return r; -} - -// Modular reduction using "classic" algorithm -function Classic(m) { this.m = m; } -function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; -} -function cRevert(x) { return x; } -function cReduce(x) { x.divRemTo(this.m,null,x); } -function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } -function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -Classic.prototype.convert = cConvert; -Classic.prototype.revert = cRevert; -Classic.prototype.reduce = cReduce; -Classic.prototype.mulTo = cMulTo; -Classic.prototype.sqrTo = cSqrTo; - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if(this.t < 1) return 0; - var x = this[0]; - if((x&1) == 0) return 0; - var y = x&3; // y == 1/x mod 2^2 - y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 - y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 - y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y>0)?this.DV-y:-y; -} - -// Montgomery reduction -function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp&0x7fff; - this.mph = this.mp>>15; - this.um = (1<<(m.DB-15))-1; - this.mt2 = 2*m.t; -} - -// xR mod m -function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t,r); - r.divRemTo(this.m,null,r); - if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); - return r; -} - -// x/R mod m -function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; -} - -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while(x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for(var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i]&0x7fff; - var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; - // use am to combine the multiply-shift-add into one call - j = i+this.m.t; - x[j] += this.m.am(0,u0,x,i,0,this.m.t); - // propagate carry - while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } - } - x.clamp(); - x.drShiftTo(this.m.t,x); - if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} - -// r = "x^2/R mod m"; x != r -function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -// r = "xy/R mod m"; x,y != r -function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - -Montgomery.prototype.convert = montConvert; -Montgomery.prototype.revert = montRevert; -Montgomery.prototype.reduce = montReduce; -Montgomery.prototype.mulTo = montMulTo; -Montgomery.prototype.sqrTo = montSqrTo; - -// (protected) true iff this is even -function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e,z) { - if(e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); -} - -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e,m) { - var z; - if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); - return this.exp(e,z); -} - -// protected -BigInteger.prototype.copyTo = bnpCopyTo; -BigInteger.prototype.fromInt = bnpFromInt; -BigInteger.prototype.fromString = bnpFromString; -BigInteger.prototype.clamp = bnpClamp; -BigInteger.prototype.dlShiftTo = bnpDLShiftTo; -BigInteger.prototype.drShiftTo = bnpDRShiftTo; -BigInteger.prototype.lShiftTo = bnpLShiftTo; -BigInteger.prototype.rShiftTo = bnpRShiftTo; -BigInteger.prototype.subTo = bnpSubTo; -BigInteger.prototype.multiplyTo = bnpMultiplyTo; -BigInteger.prototype.squareTo = bnpSquareTo; -BigInteger.prototype.divRemTo = bnpDivRemTo; -BigInteger.prototype.invDigit = bnpInvDigit; -BigInteger.prototype.isEven = bnpIsEven; -BigInteger.prototype.exp = bnpExp; - -// public -BigInteger.prototype.toString = bnToString; -BigInteger.prototype.negate = bnNegate; -BigInteger.prototype.abs = bnAbs; -BigInteger.prototype.compareTo = bnCompareTo; -BigInteger.prototype.bitLength = bnBitLength; -BigInteger.prototype.mod = bnMod; -BigInteger.prototype.modPowInt = bnModPowInt; - -// "constants" -BigInteger.ZERO = nbv(0); -BigInteger.ONE = nbv(1); -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Copyright (c) 2005-2009 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. - -// Extended JavaScript BN functions, required for RSA private ops. - -// Version 1.1: new BigInteger("0", 10) returns "proper" zero -// Version 1.2: square() API, isProbablePrime fix - -// (public) -function bnClone() { var r = nbi(); this.copyTo(r); return r; } - -// (public) return value as integer -function bnIntValue() { - if(this.s < 0) { - if(this.t == 1) return this[0]-this.DV; - else if(this.t == 0) return -1; - } - else if(this.t == 1) return this[0]; - else if(this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1]&((1<<(32-this.DB))-1))<>24; } - -// (public) return value as short (assumes DB>=16) -function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } - -// (protected) return x s.t. r^x < DV -function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } - -// (public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { - if(this.s < 0) return -1; - else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; -} - -// (protected) convert to radix string -function bnpToRadix(b) { - if(b == null) b = 10; - if(this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b,cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d,y,z); - while(y.signum() > 0) { - r = (a+z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d,y,z); - } - return z.intValue().toString(b) + r; -} - -// (protected) convert from radix string -function bnpFromRadix(s,b) { - this.fromInt(0); - if(b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b,cs), mi = false, j = 0, w = 0; - for(var i = 0; i < s.length; ++i) { - var x = intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } - } - if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); - } - if(mi) BigInteger.ZERO.subTo(this,this); -} - -// (protected) alternate constructor -function bnpFromNumber(a,b,c) { - if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); - } - } - } - else { - // new BigInteger(int,RNG) - var x = new Array(), t = a&7; - x.length = (a>>3)+1; - b.nextBytes(x); - if(t > 0) x[0] &= ((1< 0) { - if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this[i]&((1<>(p+=this.DB-8); - } - else { - d = (this[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; - } - } - return r; -} - -function bnEquals(a) { return(this.compareTo(a)==0); } -function bnMin(a) { return(this.compareTo(a)<0)?this:a; } -function bnMax(a) { return(this.compareTo(a)>0)?this:a; } - -// (protected) r = this op a (bitwise) -function bnpBitwiseTo(a,op,r) { - var i, f, m = Math.min(a.t,this.t); - for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); - if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r[i] = op(this[i],f); - r.t = this.t; - } - else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); - r.t = a.t; - } - r.s = op(this.s,a.s); - r.clamp(); -} - -// (public) this & a -function op_and(x,y) { return x&y; } -function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } - -// (public) this | a -function op_or(x,y) { return x|y; } -function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } - -// (public) this ^ a -function op_xor(x,y) { return x^y; } -function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - -// (public) this & ~a -function op_andnot(x,y) { return x&~y; } -function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } - -// (public) ~this -function bnNot() { - var r = nbi(); - for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; -} - -// (public) this << n -function bnShiftLeft(n) { - var r = nbi(); - if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); - return r; -} - -// (public) this >> n -function bnShiftRight(n) { - var r = nbi(); - if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); - return r; -} - -// return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { - if(x == 0) return -1; - var r = 0; - if((x&0xffff) == 0) { x >>= 16; r += 16; } - if((x&0xff) == 0) { x >>= 8; r += 8; } - if((x&0xf) == 0) { x >>= 4; r += 4; } - if((x&3) == 0) { x >>= 2; r += 2; } - if((x&1) == 0) ++r; - return r; -} - -// (public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { - for(var i = 0; i < this.t; ++i) - if(this[i] != 0) return i*this.DB+lbit(this[i]); - if(this.s < 0) return this.t*this.DB; - return -1; -} - -// return number of 1 bits in x -function cbit(x) { - var r = 0; - while(x != 0) { x &= x-1; ++r; } - return r; -} - -// (public) return number of set bits -function bnBitCount() { - var r = 0, x = this.s&this.DM; - for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); - return r; -} - -// (public) true iff nth bit is set -function bnTestBit(n) { - var j = Math.floor(n/this.DB); - if(j >= this.t) return(this.s!=0); - return((this[j]&(1<<(n%this.DB)))!=0); -} - -// (protected) this op (1<>= this.DB; - } - if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c += a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = (c<0)?-1:0; - if(c > 0) r[i++] = c; - else if(c < -1) r[i++] = this.DV+c; - r.t = i; - r.clamp(); -} - -// (public) this + a -function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } - -// (public) this - a -function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - -// (public) this * a -function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } - -// (public) this^2 -function bnSquare() { var r = nbi(); this.squareTo(r); return r; } - -// (public) this / a -function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } - -// (public) this % a -function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } - -// (public) [this/a,this%a] -function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a,q,r); - return new Array(q,r); -} - -// (protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { - this[this.t] = this.am(0,n-1,this,0,0,this.t); - ++this.t; - this.clamp(); -} - -// (protected) this += n << w words, this >= 0 -function bnpDAddOffset(n,w) { - if(n == 0) return; - while(this.t <= w) this[this.t++] = 0; - this[w] += n; - while(this[w] >= this.DV) { - this[w] -= this.DV; - if(++w >= this.t) this[this.t++] = 0; - ++this[w]; - } -} - -// A "null" reducer -function NullExp() {} -function nNop(x) { return x; } -function nMulTo(x,y,r) { x.multiplyTo(y,r); } -function nSqrTo(x,r) { x.squareTo(r); } - -NullExp.prototype.convert = nNop; -NullExp.prototype.revert = nNop; -NullExp.prototype.mulTo = nMulTo; -NullExp.prototype.sqrTo = nSqrTo; - -// (public) this^e -function bnPow(e) { return this.exp(e,new NullExp()); } - -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a,n,r) { - var i = Math.min(this.t+a.t,n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while(i > 0) r[--i] = 0; - var j; - for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); - for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); - r.clamp(); -} - -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a,n,r) { - --n; - var i = r.t = this.t+a.t-n; - r.s = 0; // assumes a,this >= 0 - while(--i >= 0) r[i] = 0; - for(i = Math.max(n-this.t,0); i < a.t; ++i) - r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); - r.clamp(); - r.drShiftTo(1,r); -} - -// Barrett modular reduction -function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2*m.t,this.r2); - this.mu = this.r2.divide(m); - this.m = m; -} - -function barrettConvert(x) { - if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); - else if(x.compareTo(this.m) < 0) return x; - else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } -} - -function barrettRevert(x) { return x; } - -// x = x mod m (HAC 14.42) -function barrettReduce(x) { - x.drShiftTo(this.m.t-1,this.r2); - if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } - this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); - this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); - while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); - x.subTo(this.r2,x); - while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} - -// r = x^2 mod m; x != r -function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -// r = x*y mod m; x,y != r -function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - -Barrett.prototype.convert = barrettConvert; -Barrett.prototype.revert = barrettRevert; -Barrett.prototype.reduce = barrettReduce; -Barrett.prototype.mulTo = barrettMulTo; -Barrett.prototype.sqrTo = barrettSqrTo; - -// (public) this^e % m (HAC 14.85) -function bnModPow(e,m) { - var i = e.bitLength(), k, r = nbv(1), z; - if(i <= 0) return r; - else if(i < 18) k = 1; - else if(i < 48) k = 3; - else if(i < 144) k = 4; - else if(i < 768) k = 5; - else k = 6; - if(i < 8) - z = new Classic(m); - else if(m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); - - // precomputation - var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; - } - } - - var j = e.t-1, w, is1 = true, r2 = nbi(), t; - i = nbits(e[j])-1; - while(j >= 0) { - if(i >= k1) w = (e[j]>>(i-k1))&km; - else { - w = (e[j]&((1<<(i+1))-1))<<(k1-i); - if(j > 0) w |= e[j-1]>>(this.DB+i-k1); - } - - n = k; - while((w&1) == 0) { w >>= 1; --n; } - if((i -= n) < 0) { i += this.DB; --j; } - if(is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } - else { - while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } - if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } - z.mulTo(r2,g[w],r); - } - - while(j >= 0 && (e[j]&(1< 0) { - x.rShiftTo(g,x); - y.rShiftTo(g,y); - } - while(x.signum() > 0) { - if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); - if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); - if(x.compareTo(y) >= 0) { - x.subTo(y,x); - x.rShiftTo(1,x); - } - else { - y.subTo(x,y); - y.rShiftTo(1,y); - } - } - if(g > 0) y.lShiftTo(g,y); - return y; -} - -// (protected) this % n, n < 2^26 -function bnpModInt(n) { - if(n <= 0) return 0; - var d = this.DV%n, r = (this.s<0)?n-1:0; - if(this.t > 0) - if(d == 0) r = this[0]%n; - else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; - return r; -} - -// (public) 1/this % m (HAC 14.61) -function bnModInverse(m) { - var ac = m.isEven(); - if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while(u.signum() != 0) { - while(u.isEven()) { - u.rShiftTo(1,u); - if(ac) { - if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } - a.rShiftTo(1,a); - } - else if(!b.isEven()) b.subTo(m,b); - b.rShiftTo(1,b); - } - while(v.isEven()) { - v.rShiftTo(1,v); - if(ac) { - if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } - c.rShiftTo(1,c); - } - else if(!d.isEven()) d.subTo(m,d); - d.rShiftTo(1,d); - } - if(u.compareTo(v) >= 0) { - u.subTo(v,u); - if(ac) a.subTo(c,a); - b.subTo(d,b); - } - else { - v.subTo(u,v); - if(ac) c.subTo(a,c); - d.subTo(b,d); - } - } - if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if(d.compareTo(m) >= 0) return d.subtract(m); - if(d.signum() < 0) d.addTo(m,d); else return d; - if(d.signum() < 0) return d.add(m); else return d; -} - -var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; -var lplim = (1<<26)/lowprimes[lowprimes.length-1]; - -// (public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { - var i, x = this.abs(); - if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { - for(i = 0; i < lowprimes.length; ++i) - if(x[0] == lowprimes[i]) return true; - return false; - } - if(x.isEven()) return false; - i = 1; - while(i < lowprimes.length) { - var m = lowprimes[i], j = i+1; - while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while(i < j) if(m%lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); -} - -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if(k <= 0) return false; - var r = n1.shiftRight(k); - t = (t+1)>>1; - if(t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for(var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); - var y = a.modPow(r,this); - if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while(j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2,this); - if(y.compareTo(BigInteger.ONE) == 0) return false; - } - if(y.compareTo(n1) != 0) return false; - } - } - return true; -} - -// protected -BigInteger.prototype.chunkSize = bnpChunkSize; -BigInteger.prototype.toRadix = bnpToRadix; -BigInteger.prototype.fromRadix = bnpFromRadix; -BigInteger.prototype.fromNumber = bnpFromNumber; -BigInteger.prototype.bitwiseTo = bnpBitwiseTo; -BigInteger.prototype.changeBit = bnpChangeBit; -BigInteger.prototype.addTo = bnpAddTo; -BigInteger.prototype.dMultiply = bnpDMultiply; -BigInteger.prototype.dAddOffset = bnpDAddOffset; -BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; -BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; -BigInteger.prototype.modInt = bnpModInt; -BigInteger.prototype.millerRabin = bnpMillerRabin; - -// public -BigInteger.prototype.clone = bnClone; -BigInteger.prototype.intValue = bnIntValue; -BigInteger.prototype.byteValue = bnByteValue; -BigInteger.prototype.shortValue = bnShortValue; -BigInteger.prototype.signum = bnSigNum; -BigInteger.prototype.toByteArray = bnToByteArray; -BigInteger.prototype.equals = bnEquals; -BigInteger.prototype.min = bnMin; -BigInteger.prototype.max = bnMax; -BigInteger.prototype.and = bnAnd; -BigInteger.prototype.or = bnOr; -BigInteger.prototype.xor = bnXor; -BigInteger.prototype.andNot = bnAndNot; -BigInteger.prototype.not = bnNot; -BigInteger.prototype.shiftLeft = bnShiftLeft; -BigInteger.prototype.shiftRight = bnShiftRight; -BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; -BigInteger.prototype.bitCount = bnBitCount; -BigInteger.prototype.testBit = bnTestBit; -BigInteger.prototype.setBit = bnSetBit; -BigInteger.prototype.clearBit = bnClearBit; -BigInteger.prototype.flipBit = bnFlipBit; -BigInteger.prototype.add = bnAdd; -BigInteger.prototype.subtract = bnSubtract; -BigInteger.prototype.multiply = bnMultiply; -BigInteger.prototype.divide = bnDivide; -BigInteger.prototype.remainder = bnRemainder; -BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; -BigInteger.prototype.modPow = bnModPow; -BigInteger.prototype.modInverse = bnModInverse; -BigInteger.prototype.pow = bnPow; -BigInteger.prototype.gcd = bnGCD; -BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - -// JSBN-specific extension -BigInteger.prototype.square = bnSquare; - -// BigInteger interfaces not implemented in jsbn: - -// BigInteger(int signum, byte[] magnitude) -// double doubleValue() -// float floatValue() -// int hashCode() -// long longValue() -// static BigInteger valueOf(long val) -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Depends on jsbn.js and rng.js - -// Version 1.1: support utf-8 encoding in pkcs1pad2 - -// convert a (hex) string to a bignum object -function parseBigInt(str,r) { - return new BigInteger(str,r); -} - -function linebrk(s,n) { - var ret = ""; - var i = 0; - while(i + n < s.length) { - ret += s.substring(i,i+n) + "\n"; - i += n; - } - return ret + s.substring(i,s.length); -} - -function byte2Hex(b) { - if(b < 0x10) - return "0" + b.toString(16); - else - return b.toString(16); -} - -// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint -function pkcs1pad2(s,n) { - if(n < s.length + 11) { // TODO: fix for utf-8 - alert("Message too long for RSA"); - return null; - } - var ba = new Array(); - var i = s.length - 1; - while(i >= 0 && n > 0) { - var c = s.charCodeAt(i--); - if(c < 128) { // encode using utf-8 - ba[--n] = c; - } - else if((c > 127) && (c < 2048)) { - ba[--n] = (c & 63) | 128; - ba[--n] = (c >> 6) | 192; - } - else { - ba[--n] = (c & 63) | 128; - ba[--n] = ((c >> 6) & 63) | 128; - ba[--n] = (c >> 12) | 224; - } - } - ba[--n] = 0; - var rng = new SecureRandom(); - var x = new Array(); - while(n > 2) { // random non-zero pad - x[0] = 0; - while(x[0] == 0) rng.nextBytes(x); - ba[--n] = x[0]; - } - ba[--n] = 2; - ba[--n] = 0; - return new BigInteger(ba); -} - -// PKCS#1 (OAEP) mask generation function -function oaep_mgf1_arr(seed, len, hash) -{ - var mask = '', i = 0; - - while (mask.length < len) - { - mask += hash(String.fromCharCode.apply(String, seed.concat([ - (i & 0xff000000) >> 24, - (i & 0x00ff0000) >> 16, - (i & 0x0000ff00) >> 8, - i & 0x000000ff]))); - i += 1; - } - - return mask; -} - -var SHA1_SIZE = 20; - -// PKCS#1 (OAEP) pad input string s to n bytes, and return a bigint -function oaep_pad(s, n, hash) -{ - if (s.length + 2 * SHA1_SIZE + 2 > n) - { - throw "Message too long for RSA"; - } - - var PS = '', i; - - for (i = 0; i < n - s.length - 2 * SHA1_SIZE - 2; i += 1) - { - PS += '\x00'; - } - - var DB = rstr_sha1('') + PS + '\x01' + s; - var seed = new Array(SHA1_SIZE); - new SecureRandom().nextBytes(seed); - - var dbMask = oaep_mgf1_arr(seed, DB.length, hash || rstr_sha1); - var maskedDB = []; - - for (i = 0; i < DB.length; i += 1) - { - maskedDB[i] = DB.charCodeAt(i) ^ dbMask.charCodeAt(i); - } - - var seedMask = oaep_mgf1_arr(maskedDB, seed.length, rstr_sha1); - var maskedSeed = [0]; - - for (i = 0; i < seed.length; i += 1) - { - maskedSeed[i + 1] = seed[i] ^ seedMask.charCodeAt(i); - } - - return new BigInteger(maskedSeed.concat(maskedDB)); -} - -// "empty" RSA key constructor -function RSAKey() { - this.n = null; - this.e = 0; - this.d = null; - this.p = null; - this.q = null; - this.dmp1 = null; - this.dmq1 = null; - this.coeff = null; -} - -// Set the public key fields N and e from hex strings -function RSASetPublic(N,E) { - this.isPublic = true; - if (typeof N !== "string") - { - this.n = N; - this.e = E; - } - else if(N != null && E != null && N.length > 0 && E.length > 0) { - this.n = parseBigInt(N,16); - this.e = parseInt(E,16); - } - else - alert("Invalid RSA public key"); -} - -// Perform raw public operation on "x": return x^e (mod n) -function RSADoPublic(x) { - return x.modPowInt(this.e, this.n); -} - -// Return the PKCS#1 RSA encryption of "text" as an even-length hex string -function RSAEncrypt(text) { - var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); - if(m == null) return null; - var c = this.doPublic(m); - if(c == null) return null; - var h = c.toString(16); - if((h.length & 1) == 0) return h; else return "0" + h; -} - -// Return the PKCS#1 OAEP RSA encryption of "text" as an even-length hex string -function RSAEncryptOAEP(text, hash) { - var m = oaep_pad(text, (this.n.bitLength()+7)>>3, hash); - if(m == null) return null; - var c = this.doPublic(m); - if(c == null) return null; - var h = c.toString(16); - if((h.length & 1) == 0) return h; else return "0" + h; -} - -// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string -//function RSAEncryptB64(text) { -// var h = this.encrypt(text); -// if(h) return hex2b64(h); else return null; -//} - -// protected -RSAKey.prototype.doPublic = RSADoPublic; - -// public -RSAKey.prototype.setPublic = RSASetPublic; -RSAKey.prototype.encrypt = RSAEncrypt; -RSAKey.prototype.encryptOAEP = RSAEncryptOAEP; -//RSAKey.prototype.encrypt_b64 = RSAEncryptB64; - -RSAKey.prototype.type = "RSA"; -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Depends on rsa.js and jsbn2.js - -// Version 1.1: support utf-8 decoding in pkcs1unpad2 - -// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext -function pkcs1unpad2(d,n) { - var b = d.toByteArray(); - var i = 0; - while(i < b.length && b[i] == 0) ++i; - if(b.length-i != n-1 || b[i] != 2) - return null; - ++i; - while(b[i] != 0) - if(++i >= b.length) return null; - var ret = ""; - while(++i < b.length) { - var c = b[i] & 255; - if(c < 128) { // utf-8 decode - ret += String.fromCharCode(c); - } - else if((c > 191) && (c < 224)) { - ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63)); - ++i; - } - else { - ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63)); - i += 2; - } - } - return ret; -} - -// PKCS#1 (OAEP) mask generation function -function oaep_mgf1_str(seed, len, hash) -{ - var mask = '', i = 0; - - while (mask.length < len) - { - mask += hash(seed + String.fromCharCode.apply(String, [ - (i & 0xff000000) >> 24, - (i & 0x00ff0000) >> 16, - (i & 0x0000ff00) >> 8, - i & 0x000000ff])); - i += 1; - } - - return mask; -} - -var SHA1_SIZE = 20; - -// Undo PKCS#1 (OAEP) padding and, if valid, return the plaintext -function oaep_unpad(d, n, hash) -{ - d = d.toByteArray(); - - var i; - - for (i = 0; i < d.length; i += 1) - { - d[i] &= 0xff; - } - - while (d.length < n) - { - d.unshift(0); - } - - d = String.fromCharCode.apply(String, d); - - if (d.length < 2 * SHA1_SIZE + 2) - { - throw "Cipher too short"; - } - - var maskedSeed = d.substr(1, SHA1_SIZE) - var maskedDB = d.substr(SHA1_SIZE + 1); - - var seedMask = oaep_mgf1_str(maskedDB, SHA1_SIZE, hash || rstr_sha1); - var seed = [], i; - - for (i = 0; i < maskedSeed.length; i += 1) - { - seed[i] = maskedSeed.charCodeAt(i) ^ seedMask.charCodeAt(i); - } - - var dbMask = oaep_mgf1_str(String.fromCharCode.apply(String, seed), - d.length - SHA1_SIZE, rstr_sha1); - - var DB = []; - - for (i = 0; i < maskedDB.length; i += 1) - { - DB[i] = maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i); - } - - DB = String.fromCharCode.apply(String, DB); - - if (DB.substr(0, SHA1_SIZE) !== rstr_sha1('')) - { - throw "Hash mismatch"; - } - - DB = DB.substr(SHA1_SIZE); - - var first_one = DB.indexOf('\x01'); - var last_zero = (first_one != -1) ? DB.substr(0, first_one).lastIndexOf('\x00') : -1; - - if (last_zero + 1 != first_one) - { - throw "Malformed data"; - } - - return DB.substr(first_one + 1); -} - -// Set the private key fields N, e, and d from hex strings -function RSASetPrivate(N,E,D) { - this.isPrivate = true; - if (typeof N !== "string") - { - this.n = N; - this.e = E; - this.d = D; - } - else if(N != null && E != null && N.length > 0 && E.length > 0) { - this.n = parseBigInt(N,16); - this.e = parseInt(E,16); - this.d = parseBigInt(D,16); - } - else - alert("Invalid RSA private key"); -} - -// Set the private key fields N, e, d and CRT params from hex strings -function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) { - this.isPrivate = true; - if (N == null) throw "RSASetPrivateEx N == null"; - if (E == null) throw "RSASetPrivateEx E == null"; - if (N.length == 0) throw "RSASetPrivateEx N.length == 0"; - if (E.length == 0) throw "RSASetPrivateEx E.length == 0"; - - if (N != null && E != null && N.length > 0 && E.length > 0) { - this.n = parseBigInt(N,16); - this.e = parseInt(E,16); - this.d = parseBigInt(D,16); - this.p = parseBigInt(P,16); - this.q = parseBigInt(Q,16); - this.dmp1 = parseBigInt(DP,16); - this.dmq1 = parseBigInt(DQ,16); - this.coeff = parseBigInt(C,16); - } else { - alert("Invalid RSA private key in RSASetPrivateEx"); - } -} - -// Generate a new random private key B bits long, using public expt E -function RSAGenerate(B,E) { - var rng = new SecureRandom(); - var qs = B>>1; - this.e = parseInt(E,16); - var ee = new BigInteger(E,16); - for(;;) { - for(;;) { - this.p = new BigInteger(B-qs,1,rng); - if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; - } - for(;;) { - this.q = new BigInteger(qs,1,rng); - if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break; - } - if(this.p.compareTo(this.q) <= 0) { - var t = this.p; - this.p = this.q; - this.q = t; - } - var p1 = this.p.subtract(BigInteger.ONE); // p1 = p - 1 - var q1 = this.q.subtract(BigInteger.ONE); // q1 = q - 1 - var phi = p1.multiply(q1); - if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { - this.n = this.p.multiply(this.q); // this.n = p * q - this.d = ee.modInverse(phi); // this.d = - this.dmp1 = this.d.mod(p1); // this.dmp1 = d mod (p - 1) - this.dmq1 = this.d.mod(q1); // this.dmq1 = d mod (q - 1) - this.coeff = this.q.modInverse(this.p); // this.coeff = (q ^ -1) mod p - break; - } - } - this.isPrivate = true; -} - -// Perform raw private operation on "x": return x^d (mod n) -function RSADoPrivate(x) { - if(this.p == null || this.q == null) - return x.modPow(this.d, this.n); - - // TODO: re-calculate any missing CRT params - var xp = x.mod(this.p).modPow(this.dmp1, this.p); // xp=cp? - var xq = x.mod(this.q).modPow(this.dmq1, this.q); // xq=cq? - - while(xp.compareTo(xq) < 0) - xp = xp.add(this.p); - // NOTE: - // xp.subtract(xq) => cp -cq - // xp.subtract(xq).multiply(this.coeff).mod(this.p) => (cp - cq) * u mod p = h - // xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq) => cq + (h * q) = M - return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); -} - -// Return the PKCS#1 RSA decryption of "ctext". -// "ctext" is an even-length hex string and the output is a plain string. -function RSADecrypt(ctext) { - var c = parseBigInt(ctext, 16); - var m = this.doPrivate(c); - if(m == null) return null; - return pkcs1unpad2(m, (this.n.bitLength()+7)>>3); -} - -// Return the PKCS#1 OAEP RSA decryption of "ctext". -// "ctext" is an even-length hex string and the output is a plain string. -function RSADecryptOAEP(ctext, hash) { - var c = parseBigInt(ctext, 16); - var m = this.doPrivate(c); - if(m == null) return null; - return oaep_unpad(m, (this.n.bitLength()+7)>>3, hash); -} - -// Return the PKCS#1 RSA decryption of "ctext". -// "ctext" is a Base64-encoded string and the output is a plain string. -//function RSAB64Decrypt(ctext) { -// var h = b64tohex(ctext); -// if(h) return this.decrypt(h); else return null; -//} - -// protected -RSAKey.prototype.doPrivate = RSADoPrivate; - -// public -RSAKey.prototype.setPrivate = RSASetPrivate; -RSAKey.prototype.setPrivateEx = RSASetPrivateEx; -RSAKey.prototype.generate = RSAGenerate; -RSAKey.prototype.decrypt = RSADecrypt; -RSAKey.prototype.decryptOAEP = RSADecryptOAEP; -//RSAKey.prototype.b64_decrypt = RSAB64Decrypt; -/*! rsapem-1.1.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -// -// rsa-pem.js - adding function for reading/writing PKCS#1 PEM private key -// to RSAKey class. -// -// version: 1.1.1 (2013-Apr-12) -// -// Copyright (c) 2010-2013 Kenji Urushima (kenji.urushima@gmail.com) -// -// This software is licensed under the terms of the MIT License. -// http://kjur.github.com/jsrsasign/license/ -// -// The above copyright and license notice shall be -// included in all copies or substantial portions of the Software. -// -// -// Depends on: -// -// -// -// _RSApem_pemToBase64(sPEM) -// -// removing PEM header, PEM footer and space characters including -// new lines from PEM formatted RSA private key string. -// - -/** - * @fileOverview - * @name rsapem-1.1.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version 1.1 - * @license MIT License - */ -function _rsapem_pemToBase64(sPEMPrivateKey) { - var s = sPEMPrivateKey; - s = s.replace("-----BEGIN RSA PRIVATE KEY-----", ""); - s = s.replace("-----END RSA PRIVATE KEY-----", ""); - s = s.replace(/[ \n]+/g, ""); - return s; -} - -function _rsapem_getPosArrayOfChildrenFromHex(hPrivateKey) { - var a = new Array(); - var v1 = ASN1HEX.getStartPosOfV_AtObj(hPrivateKey, 0); - var n1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, v1); - var e1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, n1); - var d1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, e1); - var p1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, d1); - var q1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, p1); - var dp1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, q1); - var dq1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, dp1); - var co1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, dq1); - a.push(v1, n1, e1, d1, p1, q1, dp1, dq1, co1); - return a; -} - -function _rsapem_getHexValueArrayOfChildrenFromHex(hPrivateKey) { - var posArray = _rsapem_getPosArrayOfChildrenFromHex(hPrivateKey); - var v = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[0]); - var n = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[1]); - var e = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[2]); - var d = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[3]); - var p = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[4]); - var q = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[5]); - var dp = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[6]); - var dq = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[7]); - var co = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[8]); - var a = new Array(); - a.push(v, n, e, d, p, q, dp, dq, co); - return a; -} - -/** - * read RSA private key from a ASN.1 hexadecimal string - * @name readPrivateKeyFromASN1HexString - * @memberOf RSAKey# - * @function - * @param {String} keyHex ASN.1 hexadecimal string of PKCS#1 private key. - * @since 1.1.1 - */ -function _rsapem_readPrivateKeyFromASN1HexString(keyHex) { - var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex); - this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]); -} - -/** - * read PKCS#1 private key from a string - * @name readPrivateKeyFromPEMString - * @memberOf RSAKey# - * @function - * @param {String} keyPEM string of PKCS#1 private key. - */ -function _rsapem_readPrivateKeyFromPEMString(keyPEM) { - var keyB64 = _rsapem_pemToBase64(keyPEM); - var keyHex = b64tohex(keyB64) // depends base64.js - var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex); - this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]); -} - -RSAKey.prototype.readPrivateKeyFromPEMString = _rsapem_readPrivateKeyFromPEMString; -RSAKey.prototype.readPrivateKeyFromASN1HexString = _rsapem_readPrivateKeyFromASN1HexString; -/*! rsasign-1.2.7.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -var _RE_HEXDECONLY=new RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(d,e,a){var b=function(f){return KJUR.crypto.Util.hashString(f,a)};var c=b(d);return KJUR.crypto.Util.getPaddedDigestInfoHex(c,a,e)}function _zeroPaddingOfSignature(e,d){var c="";var a=d/4-e.length;for(var b=0;b>24,(d&16711680)>>16,(d&65280)>>8,d&255]))));d+=1}return b}function _rsasign_signStringPSS(e,a,d){var c=function(f){return KJUR.crypto.Util.hashHex(f,a)};var b=c(rstrtohex(e));if(d===undefined){d=-1}return this.signWithMessageHashPSS(b,a,d)}function _rsasign_signWithMessageHashPSS(l,a,k){var b=hextorstr(l);var g=b.length;var m=this.n.bitLength()-1;var c=Math.ceil(m/8);var d;var o=function(i){return KJUR.crypto.Util.hashHex(i,a)};if(k===-1||k===undefined){k=g}else{if(k===-2){k=c-g-2}else{if(k<-2){throw"invalid salt length"}}}if(c<(g+k+2)){throw"data too long"}var f="";if(k>0){f=new Array(k);new SecureRandom().nextBytes(f);f=String.fromCharCode.apply(String,f)}var n=hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+b+f)));var j=[];for(d=0;d>(8*c-m))&255;q[0]&=~p;for(d=0;dthis.n.bitLength()){return 0}var i=this.doPublic(b);var e=i.toString(16).replace(/^1f+00/,"");var g=_rsasign_getAlgNameAndHashFromHexDisgestInfo(e);if(g.length==0){return false}var d=g[0];var h=g[1];var a=function(k){return KJUR.crypto.Util.hashString(k,d)};var c=a(f);return(h==c)}function _rsasign_verifyWithMessageHash(e,a){a=a.replace(_RE_HEXDECONLY,"");a=a.replace(/[ \n]+/g,"");var b=parseBigInt(a,16);if(b.bitLength()>this.n.bitLength()){return 0}var h=this.doPublic(b);var g=h.toString(16).replace(/^1f+00/,"");var c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(g);if(c.length==0){return false}var d=c[0];var f=c[1];return(f==e)}function _rsasign_verifyStringPSS(c,b,a,f){var e=function(g){return KJUR.crypto.Util.hashHex(g,a)};var d=e(rstrtohex(c));if(f===undefined){f=-1}return this.verifyWithMessageHashPSS(d,b,a,f)}function _rsasign_verifyWithMessageHashPSS(f,s,l,c){var k=new BigInteger(s,16);if(k.bitLength()>this.n.bitLength()){return false}var r=function(i){return KJUR.crypto.Util.hashHex(i,l)};var j=hextorstr(f);var h=j.length;var g=this.n.bitLength()-1;var m=Math.ceil(g/8);var q;if(c===-1||c===undefined){c=h}else{if(c===-2){c=m-h-2}else{if(c<-2){throw"invalid salt length"}}}if(m<(h+c+2)){throw"data too long"}var a=this.doPublic(k).toByteArray();for(q=0;q>(8*m-g))&255;if((d.charCodeAt(0)&p)!==0){throw"bits beyond keysize not zero"}var n=pss_mgf1_str(e,d.length,r);var o=[];for(q=0;qMIT License - */ - -/* - * MEMO: - * f('3082025b02...', 2) ... 82025b ... 3bytes - * f('020100', 2) ... 01 ... 1byte - * f('0203001...', 2) ... 03 ... 1byte - * f('02818003...', 2) ... 8180 ... 2bytes - * f('3080....0000', 2) ... 80 ... -1 - * - * Requirements: - * - ASN.1 type octet length MUST be 1. - * (i.e. ASN.1 primitives like SET, SEQUENCE, INTEGER, OCTETSTRING ...) - */ - -/** - * ASN.1 DER encoded hexadecimal string utility class - * @name ASN1HEX - * @class ASN.1 DER encoded hexadecimal string utility class - * @since jsrsasign 1.1 - */ -var ASN1HEX = new function() { - /** - * get byte length for ASN.1 L(length) bytes - * @name getByteLengthOfL_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return byte length for ASN.1 L(length) bytes - */ - this.getByteLengthOfL_AtObj = function(s, pos) { - if (s.substring(pos + 2, pos + 3) != '8') return 1; - var i = parseInt(s.substring(pos + 3, pos + 4)); - if (i == 0) return -1; // length octet '80' indefinite length - if (0 < i && i < 10) return i + 1; // including '8?' octet; - return -2; // malformed format - }; - - /** - * get hexadecimal string for ASN.1 L(length) bytes - * @name getHexOfL_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return {String} hexadecimal string for ASN.1 L(length) bytes - */ - this.getHexOfL_AtObj = function(s, pos) { - var len = this.getByteLengthOfL_AtObj(s, pos); - if (len < 1) return ''; - return s.substring(pos + 2, pos + 2 + len * 2); - }; - - // getting ASN.1 length value at the position 'idx' of - // hexa decimal string 's'. - // - // f('3082025b02...', 0) ... 82025b ... ??? - // f('020100', 0) ... 01 ... 1 - // f('0203001...', 0) ... 03 ... 3 - // f('02818003...', 0) ... 8180 ... 128 - /** - * get integer value of ASN.1 length for ASN.1 data - * @name getIntOfL_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return ASN.1 L(length) integer value - */ - this.getIntOfL_AtObj = function(s, pos) { - var hLength = this.getHexOfL_AtObj(s, pos); - if (hLength == '') return -1; - var bi; - if (parseInt(hLength.substring(0, 1)) < 8) { - bi = new BigInteger(hLength, 16); - } else { - bi = new BigInteger(hLength.substring(2), 16); - } - return bi.intValue(); - }; - - /** - * get ASN.1 value starting string position for ASN.1 object refered by index 'idx'. - * @name getStartPosOfV_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - */ - this.getStartPosOfV_AtObj = function(s, pos) { - var l_len = this.getByteLengthOfL_AtObj(s, pos); - if (l_len < 0) return l_len; - return pos + (l_len + 1) * 2; - }; - - /** - * get hexadecimal string of ASN.1 V(value) - * @name getHexOfV_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return {String} hexadecimal string of ASN.1 value. - */ - this.getHexOfV_AtObj = function(s, pos) { - var pos1 = this.getStartPosOfV_AtObj(s, pos); - var len = this.getIntOfL_AtObj(s, pos); - return s.substring(pos1, pos1 + len * 2); - }; - - /** - * get hexadecimal string of ASN.1 TLV at - * @name getHexOfTLV_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return {String} hexadecimal string of ASN.1 TLV. - * @since 1.1 - */ - this.getHexOfTLV_AtObj = function(s, pos) { - var hT = s.substr(pos, 2); - var hL = this.getHexOfL_AtObj(s, pos); - var hV = this.getHexOfV_AtObj(s, pos); - return hT + hL + hV; - }; - - /** - * get next sibling starting index for ASN.1 object string - * @name getPosOfNextSibling_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return next sibling starting index for ASN.1 object string - */ - this.getPosOfNextSibling_AtObj = function(s, pos) { - var pos1 = this.getStartPosOfV_AtObj(s, pos); - var len = this.getIntOfL_AtObj(s, pos); - return pos1 + len * 2; - }; - - /** - * get array of indexes of child ASN.1 objects - * @name getPosArrayOfChildren_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} start string index of ASN.1 object - * @return {Array of Number} array of indexes for childen of ASN.1 objects - */ - this.getPosArrayOfChildren_AtObj = function(h, pos) { - var a = new Array(); - var p0 = this.getStartPosOfV_AtObj(h, pos); - a.push(p0); - - var len = this.getIntOfL_AtObj(h, pos); - var p = p0; - var k = 0; - while (1) { - var pNext = this.getPosOfNextSibling_AtObj(h, p); - if (pNext == null || (pNext - p0 >= (len * 2))) break; - if (k >= 200) break; - - a.push(pNext); - p = pNext; - - k++; - } - - return a; - }; - - /** - * get string index of nth child object of ASN.1 object refered by h, idx - * @name getNthChildIndex_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} idx start string index of ASN.1 object - * @param {Number} nth for child - * @return {Number} string index of nth child. - * @since 1.1 - */ - this.getNthChildIndex_AtObj = function(h, idx, nth) { - var a = this.getPosArrayOfChildren_AtObj(h, idx); - return a[nth]; - }; - - // ========== decendant methods ============================== - /** - * get string index of nth child object of ASN.1 object refered by h, idx - * @name getDecendantIndexByNthList - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} currentIndex start string index of ASN.1 object - * @param {Array of Number} nthList array list of nth - * @return {Number} string index refered by nthList - * @since 1.1 - * @example - * The "nthList" is a index list of structured ASN.1 object - * reference. Here is a sample structure and "nthList"s which - * refers each objects. - * - * SQUENCE - - * SEQUENCE - [0] - * IA5STRING 000 - [0, 0] - * UTF8STRING 001 - [0, 1] - * SET - [1] - * IA5STRING 010 - [1, 0] - * UTF8STRING 011 - [1, 1] - */ - this.getDecendantIndexByNthList = function(h, currentIndex, nthList) { - if (nthList.length == 0) { - return currentIndex; - } - var firstNth = nthList.shift(); - var a = this.getPosArrayOfChildren_AtObj(h, currentIndex); - return this.getDecendantIndexByNthList(h, a[firstNth], nthList); - }; - - /** - * get hexadecimal string of ASN.1 TLV refered by current index and nth index list. - * @name getDecendantHexTLVByNthList - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} currentIndex start string index of ASN.1 object - * @param {Array of Number} nthList array list of nth - * @return {Number} hexadecimal string of ASN.1 TLV refered by nthList - * @since 1.1 - */ - this.getDecendantHexTLVByNthList = function(h, currentIndex, nthList) { - var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList); - return this.getHexOfTLV_AtObj(h, idx); - }; - - /** - * get hexadecimal string of ASN.1 V refered by current index and nth index list. - * @name getDecendantHexVByNthList - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} currentIndex start string index of ASN.1 object - * @param {Array of Number} nthList array list of nth - * @return {Number} hexadecimal string of ASN.1 V refered by nthList - * @since 1.1 - */ - this.getDecendantHexVByNthList = function(h, currentIndex, nthList) { - var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList); - return this.getHexOfV_AtObj(h, idx); - }; -}; - -/* - * @since asn1hex 1.1.4 - */ -ASN1HEX.getVbyList = function(h, currentIndex, nthList, checkingTag) { - var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList); - if (idx === undefined) { - throw "can't find nthList object"; - } - if (checkingTag !== undefined) { - if (h.substr(idx, 2) != checkingTag) { - throw "checking tag doesn't match: " + - h.substr(idx,2) + "!=" + checkingTag; - } - } - return this.getHexOfV_AtObj(h, idx); -}; - -/** - * get OID string from hexadecimal encoded value - * @name hextooidstr - * @memberOf ASN1HEX - * @function - * @param {String} hex hexadecmal string of ASN.1 DER encoded OID value - * @return {String} OID string (ex. '1.2.3.4.567') - * @since asn1hex 1.1.5 - */ -ASN1HEX.hextooidstr = function(hex) { - var zeroPadding = function(s, len) { - if (s.length >= len) return s; - return new Array(len - s.length + 1).join('0') + s; - }; - - var a = []; - - // a[0], a[1] - var hex0 = hex.substr(0, 2); - var i0 = parseInt(hex0, 16); - a[0] = new String(Math.floor(i0 / 40)); - a[1] = new String(i0 % 40); - - // a[2]..a[n] - var hex1 = hex.substr(2); - var b = []; - for (var i = 0; i < hex1.length / 2; i++) { - b.push(parseInt(hex1.substr(i * 2, 2), 16)); - } - var c = []; - var cbin = ""; - for (var i = 0; i < b.length; i++) { - if (b[i] & 0x80) { - cbin = cbin + zeroPadding((b[i] & 0x7f).toString(2), 7); - } else { - cbin = cbin + zeroPadding((b[i] & 0x7f).toString(2), 7); - c.push(new String(parseInt(cbin, 2))); - cbin = ""; - } - } - - var s = a.join("."); - if (c.length > 0) s = s + "." + c.join("."); - return s; -}; - -/*! x509-1.1.3.js (c) 2012-2014 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -/* - * x509.js - X509 class to read subject public key from certificate. - * - * Copyright (c) 2010-2014 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsrsasign/license - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - */ - -/** - * @fileOverview - * @name x509-1.1.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version x509 1.1.3 (2014-May-17) - * @since jsrsasign 1.x.x - * @license MIT License - */ - -/* - * Depends: - * base64.js - * rsa.js - * asn1hex.js - */ - -/** - * X.509 certificate class.
- * @class X.509 certificate class - * @property {RSAKey} subjectPublicKeyRSA Tom Wu's RSAKey object - * @property {String} subjectPublicKeyRSA_hN hexadecimal string for modulus of RSA public key - * @property {String} subjectPublicKeyRSA_hE hexadecimal string for public exponent of RSA public key - * @property {String} hex hexacedimal string for X.509 certificate. - * @author Kenji Urushima - * @version 1.0.1 (08 May 2012) - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - */ -function X509() { - this.subjectPublicKeyRSA = null; - this.subjectPublicKeyRSA_hN = null; - this.subjectPublicKeyRSA_hE = null; - this.hex = null; - - // ===== get basic fields from hex ===================================== - - /** - * get hexadecimal string of serialNumber field of certificate.
- * @name getSerialNumberHex - * @memberOf X509# - * @function - */ - this.getSerialNumberHex = function() { - return ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 1]); - }; - - /** - * get hexadecimal string of issuer field TLV of certificate.
- * @name getIssuerHex - * @memberOf X509# - * @function - */ - this.getIssuerHex = function() { - return ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 3]); - }; - - /** - * get string of issuer field of certificate.
- * @name getIssuerString - * @memberOf X509# - * @function - */ - this.getIssuerString = function() { - return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 3])); - }; - - /** - * get hexadecimal string of subject field of certificate.
- * @name getSubjectHex - * @memberOf X509# - * @function - */ - this.getSubjectHex = function() { - return ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 5]); - }; - - /** - * get string of subject field of certificate.
- * @name getSubjectString - * @memberOf X509# - * @function - */ - this.getSubjectString = function() { - return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 5])); - }; - - /** - * get notBefore field string of certificate.
- * @name getNotBefore - * @memberOf X509# - * @function - */ - this.getNotBefore = function() { - var s = ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 4, 0]); - s = s.replace(/(..)/g, "%$1"); - s = decodeURIComponent(s); - return s; - }; - - /** - * get notAfter field string of certificate.
- * @name getNotAfter - * @memberOf X509# - * @function - */ - this.getNotAfter = function() { - var s = ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 4, 1]); - s = s.replace(/(..)/g, "%$1"); - s = decodeURIComponent(s); - return s; - }; - - // ===== read certificate public key ========================== - - // ===== read certificate ===================================== - /** - * read PEM formatted X.509 certificate from string.
- * @name readCertPEM - * @memberOf X509# - * @function - * @param {String} sCertPEM string for PEM formatted X.509 certificate - */ - this.readCertPEM = function(sCertPEM) { - var hCert = X509.pemToHex(sCertPEM); - var a = X509.getPublicKeyHexArrayFromCertHex(hCert); - var rsa = new RSAKey(); - rsa.setPublic(a[0], a[1]); - this.subjectPublicKeyRSA = rsa; - this.subjectPublicKeyRSA_hN = a[0]; - this.subjectPublicKeyRSA_hE = a[1]; - this.hex = hCert; - }; - - this.readCertPEMWithoutRSAInit = function(sCertPEM) { - var hCert = X509.pemToHex(sCertPEM); - var a = X509.getPublicKeyHexArrayFromCertHex(hCert); - this.subjectPublicKeyRSA.setPublic(a[0], a[1]); - this.subjectPublicKeyRSA_hN = a[0]; - this.subjectPublicKeyRSA_hE = a[1]; - this.hex = hCert; - }; -}; - -X509.pemToBase64 = function(sCertPEM) { - var s = sCertPEM; - s = s.replace("-----BEGIN CERTIFICATE-----", ""); - s = s.replace("-----END CERTIFICATE-----", ""); - s = s.replace(/[ \n]+/g, ""); - return s; -}; - -X509.pemToHex = function(sCertPEM) { - var b64Cert = X509.pemToBase64(sCertPEM); - var hCert = b64tohex(b64Cert); - return hCert; -}; - -// NOTE: Without BITSTRING encapsulation. -X509.getSubjectPublicKeyPosFromCertHex = function(hCert) { - var pInfo = X509.getSubjectPublicKeyInfoPosFromCertHex(hCert); - if (pInfo == -1) return -1; - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pInfo); - if (a.length != 2) return -1; - var pBitString = a[1]; - if (hCert.substring(pBitString, pBitString + 2) != '03') return -1; - var pBitStringV = ASN1HEX.getStartPosOfV_AtObj(hCert, pBitString); - - if (hCert.substring(pBitStringV, pBitStringV + 2) != '00') return -1; - return pBitStringV + 2; -}; - -// NOTE: privateKeyUsagePeriod field of X509v2 not supported. -// NOTE: v1 and v3 supported -X509.getSubjectPublicKeyInfoPosFromCertHex = function(hCert) { - var pTbsCert = ASN1HEX.getStartPosOfV_AtObj(hCert, 0); - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pTbsCert); - if (a.length < 1) return -1; - if (hCert.substring(a[0], a[0] + 10) == "a003020102") { // v3 - if (a.length < 6) return -1; - return a[6]; - } else { - if (a.length < 5) return -1; - return a[5]; - } -}; - -X509.getPublicKeyHexArrayFromCertHex = function(hCert) { - var p = X509.getSubjectPublicKeyPosFromCertHex(hCert); - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, p); - if (a.length != 2) return []; - var hN = ASN1HEX.getHexOfV_AtObj(hCert, a[0]); - var hE = ASN1HEX.getHexOfV_AtObj(hCert, a[1]); - if (hN != null && hE != null) { - return [hN, hE]; - } else { - return []; - } -}; - -X509.getHexTbsCertificateFromCert = function(hCert) { - var pTbsCert = ASN1HEX.getStartPosOfV_AtObj(hCert, 0); - return pTbsCert; -}; - -X509.getPublicKeyHexArrayFromCertPEM = function(sCertPEM) { - var hCert = X509.pemToHex(sCertPEM); - var a = X509.getPublicKeyHexArrayFromCertHex(hCert); - return a; -}; - -X509.hex2dn = function(hDN) { - var s = ""; - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hDN, 0); - for (var i = 0; i < a.length; i++) { - var hRDN = ASN1HEX.getHexOfTLV_AtObj(hDN, a[i]); - s = s + "/" + X509.hex2rdn(hRDN); - } - return s; -}; - -X509.hex2rdn = function(hRDN) { - var hType = ASN1HEX.getDecendantHexTLVByNthList(hRDN, 0, [0, 0]); - var hValue = ASN1HEX.getDecendantHexVByNthList(hRDN, 0, [0, 1]); - var type = ""; - try { type = X509.DN_ATTRHEX[hType]; } catch (ex) { type = hType; } - hValue = hValue.replace(/(..)/g, "%$1"); - var value = decodeURIComponent(hValue); - return type + "=" + value; -}; - -X509.DN_ATTRHEX = { - "0603550406": "C", - "060355040a": "O", - "060355040b": "OU", - "0603550403": "CN", - "0603550405": "SN", - "0603550408": "ST", - "0603550407": "L", -}; - -/** - * get RSAKey/ECDSA public key object from PEM certificate string - * @name getPublicKeyFromCertPEM - * @memberOf X509 - * @function - * @param {String} sCertPEM PEM formatted RSA/ECDSA/DSA X.509 certificate - * @return returns RSAKey/KJUR.crypto.{ECDSA,DSA} object of public key - * @since x509 1.1.1 - * @description - * NOTE: DSA is also supported since x509 1.1.2. - */ -X509.getPublicKeyFromCertPEM = function(sCertPEM) { - var info = X509.getPublicKeyInfoPropOfCertPEM(sCertPEM); - - if (info.algoid == "2a864886f70d010101") { // RSA - var aRSA = KEYUTIL.parsePublicRawRSAKeyHex(info.keyhex); - var key = new RSAKey(); - key.setPublic(aRSA.n, aRSA.e); - return key; - } else if (info.algoid == "2a8648ce3d0201") { // ECC - var curveName = KJUR.crypto.OID.oidhex2name[info.algparam]; - var key = new KJUR.crypto.ECDSA({'curve': curveName, 'info': info.keyhex}); - key.setPublicKeyHex(info.keyhex); - return key; - } else if (info.algoid == "2a8648ce380401") { // DSA 1.2.840.10040.4.1 - var p = ASN1HEX.getVbyList(info.algparam, 0, [0], "02"); - var q = ASN1HEX.getVbyList(info.algparam, 0, [1], "02"); - var g = ASN1HEX.getVbyList(info.algparam, 0, [2], "02"); - var y = ASN1HEX.getHexOfV_AtObj(info.keyhex, 0); - y = y.substr(2); - var key = new KJUR.crypto.DSA(); - key.setPublic(new BigInteger(p, 16), - new BigInteger(q, 16), - new BigInteger(g, 16), - new BigInteger(y, 16)); - return key; - } else { - throw "unsupported key"; - } -}; - -/** - * get public key information from PEM certificate - * @name getPublicKeyInfoPropOfCertPEM - * @memberOf X509 - * @function - * @param {String} sCertPEM string of PEM formatted certificate - * @return {Hash} hash of information for public key - * @since x509 1.1.1 - * @description - * Resulted associative array has following properties: - *
    - *
  • algoid - hexadecimal string of OID of asymmetric key algorithm
  • - *
  • algparam - hexadecimal string of OID of ECC curve name or null
  • - *
  • keyhex - hexadecimal string of key in the certificate
  • - *
- * @since x509 1.1.1 - */ -X509.getPublicKeyInfoPropOfCertPEM = function(sCertPEM) { - var result = {}; - result.algparam = null; - var hCert = X509.pemToHex(sCertPEM); - - // 1. Certificate ASN.1 - var a1 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, 0); - if (a1.length != 3) - throw "malformed X.509 certificate PEM (code:001)"; // not 3 item of seq Cert - - // 2. tbsCertificate - if (hCert.substr(a1[0], 2) != "30") - throw "malformed X.509 certificate PEM (code:002)"; // tbsCert not seq - - var a2 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a1[0]); - - // 3. subjectPublicKeyInfo - if (a2.length < 7) - throw "malformed X.509 certificate PEM (code:003)"; // no subjPubKeyInfo - - var a3 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a2[6]); - - if (a3.length != 2) - throw "malformed X.509 certificate PEM (code:004)"; // not AlgId and PubKey - - // 4. AlgId - var a4 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a3[0]); - - if (a4.length != 2) - throw "malformed X.509 certificate PEM (code:005)"; // not 2 item in AlgId - - result.algoid = ASN1HEX.getHexOfV_AtObj(hCert, a4[0]); - - if (hCert.substr(a4[1], 2) == "06") { // EC - result.algparam = ASN1HEX.getHexOfV_AtObj(hCert, a4[1]); - } else if (hCert.substr(a4[1], 2) == "30") { // DSA - result.algparam = ASN1HEX.getHexOfTLV_AtObj(hCert, a4[1]); - } - - // 5. Public Key Hex - if (hCert.substr(a3[1], 2) != "03") - throw "malformed X.509 certificate PEM (code:006)"; // not bitstring - - var unusedBitAndKeyHex = ASN1HEX.getHexOfV_AtObj(hCert, a3[1]); - result.keyhex = unusedBitAndKeyHex.substr(2); - - return result; -}; - -/* - X509.prototype.readCertPEM = _x509_readCertPEM; - X509.prototype.readCertPEMWithoutRSAInit = _x509_readCertPEMWithoutRSAInit; - X509.prototype.getSerialNumberHex = _x509_getSerialNumberHex; - X509.prototype.getIssuerHex = _x509_getIssuerHex; - X509.prototype.getSubjectHex = _x509_getSubjectHex; - X509.prototype.getIssuerString = _x509_getIssuerString; - X509.prototype.getSubjectString = _x509_getSubjectString; - X509.prototype.getNotBefore = _x509_getNotBefore; - X509.prototype.getNotAfter = _x509_getNotAfter; -*/ -/*! crypto-1.1.5.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -/* - * crypto.js - Cryptographic Algorithm Provider class - * - * Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsrsasign/license - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - */ - -/** - * @fileOverview - * @name crypto-1.1.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version 1.1.5 (2013-Oct-06) - * @since jsrsasign 2.2 - * @license MIT License - */ - -/** - * kjur's class library name space - * @name KJUR - * @namespace kjur's class library name space - */ -if (typeof KJUR == "undefined" || !KJUR) KJUR = {}; -/** - * kjur's cryptographic algorithm provider library name space - *

- * This namespace privides following crytpgrahic classes. - *

    - *
  • {@link KJUR.crypto.MessageDigest} - Java JCE(cryptograhic extension) style MessageDigest class
  • - *
  • {@link KJUR.crypto.Signature} - Java JCE(cryptograhic extension) style Signature class
  • - *
  • {@link KJUR.crypto.Util} - cryptographic utility functions and properties
  • - *
- * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. - *

- * @name KJUR.crypto - * @namespace - */ -if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) KJUR.crypto = {}; - -/** - * static object for cryptographic function utilities - * @name KJUR.crypto.Util - * @class static object for cryptographic function utilities - * @property {Array} DIGESTINFOHEAD PKCS#1 DigestInfo heading hexadecimal bytes for each hash algorithms - * @property {Array} DEFAULTPROVIDER associative array of default provider name for each hash and signature algorithms - * @description - */ -KJUR.crypto.Util = new function() { - this.DIGESTINFOHEAD = { - 'sha1': "3021300906052b0e03021a05000414", - 'sha224': "302d300d06096086480165030402040500041c", - 'sha256': "3031300d060960864801650304020105000420", - 'sha384': "3041300d060960864801650304020205000430", - 'sha512': "3051300d060960864801650304020305000440", - 'md2': "3020300c06082a864886f70d020205000410", - 'md5': "3020300c06082a864886f70d020505000410", - 'ripemd160': "3021300906052b2403020105000414", - }; - - /* - * @since crypto 1.1.1 - */ - this.DEFAULTPROVIDER = { - 'md5': 'cryptojs', - 'sha1': 'cryptojs', - 'sha224': 'cryptojs', - 'sha256': 'cryptojs', - 'sha384': 'cryptojs', - 'sha512': 'cryptojs', - 'ripemd160': 'cryptojs', - 'hmacmd5': 'cryptojs', - 'hmacsha1': 'cryptojs', - 'hmacsha224': 'cryptojs', - 'hmacsha256': 'cryptojs', - 'hmacsha384': 'cryptojs', - 'hmacsha512': 'cryptojs', - 'hmacripemd160': 'cryptojs', - - 'MD5withRSA': 'cryptojs/jsrsa', - 'SHA1withRSA': 'cryptojs/jsrsa', - 'SHA224withRSA': 'cryptojs/jsrsa', - 'SHA256withRSA': 'cryptojs/jsrsa', - 'SHA384withRSA': 'cryptojs/jsrsa', - 'SHA512withRSA': 'cryptojs/jsrsa', - 'RIPEMD160withRSA': 'cryptojs/jsrsa', - - 'MD5withECDSA': 'cryptojs/jsrsa', - 'SHA1withECDSA': 'cryptojs/jsrsa', - 'SHA224withECDSA': 'cryptojs/jsrsa', - 'SHA256withECDSA': 'cryptojs/jsrsa', - 'SHA384withECDSA': 'cryptojs/jsrsa', - 'SHA512withECDSA': 'cryptojs/jsrsa', - 'RIPEMD160withECDSA': 'cryptojs/jsrsa', - - 'SHA1withDSA': 'cryptojs/jsrsa', - 'SHA224withDSA': 'cryptojs/jsrsa', - 'SHA256withDSA': 'cryptojs/jsrsa', - - 'MD5withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA1withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA224withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA256withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA384withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA512withRSAandMGF1': 'cryptojs/jsrsa', - 'RIPEMD160withRSAandMGF1': 'cryptojs/jsrsa', - }; - - /* - * @since crypto 1.1.2 - */ - this.CRYPTOJSMESSAGEDIGESTNAME = { - 'md5': 'CryptoJS.algo.MD5', - 'sha1': 'CryptoJS.algo.SHA1', - 'sha224': 'CryptoJS.algo.SHA224', - 'sha256': 'CryptoJS.algo.SHA256', - 'sha384': 'CryptoJS.algo.SHA384', - 'sha512': 'CryptoJS.algo.SHA512', - 'ripemd160': 'CryptoJS.algo.RIPEMD160' - }; - - /** - * get hexadecimal DigestInfo - * @name getDigestInfoHex - * @memberOf KJUR.crypto.Util - * @function - * @param {String} hHash hexadecimal hash value - * @param {String} alg hash algorithm name (ex. 'sha1') - * @return {String} hexadecimal string DigestInfo ASN.1 structure - */ - this.getDigestInfoHex = function(hHash, alg) { - if (typeof this.DIGESTINFOHEAD[alg] == "undefined") - throw "alg not supported in Util.DIGESTINFOHEAD: " + alg; - return this.DIGESTINFOHEAD[alg] + hHash; - }; - - /** - * get PKCS#1 padded hexadecimal DigestInfo - * @name getPaddedDigestInfoHex - * @memberOf KJUR.crypto.Util - * @function - * @param {String} hHash hexadecimal hash value of message to be signed - * @param {String} alg hash algorithm name (ex. 'sha1') - * @param {Integer} keySize key bit length (ex. 1024) - * @return {String} hexadecimal string of PKCS#1 padded DigestInfo - */ - this.getPaddedDigestInfoHex = function(hHash, alg, keySize) { - var hDigestInfo = this.getDigestInfoHex(hHash, alg); - var pmStrLen = keySize / 4; // minimum PM length - - if (hDigestInfo.length + 22 > pmStrLen) // len(0001+ff(*8)+00+hDigestInfo)=22 - throw "key is too short for SigAlg: keylen=" + keySize + "," + alg; - - var hHead = "0001"; - var hTail = "00" + hDigestInfo; - var hMid = ""; - var fLen = pmStrLen - hHead.length - hTail.length; - for (var i = 0; i < fLen; i += 2) { - hMid += "ff"; - } - var hPaddedMessage = hHead + hMid + hTail; - return hPaddedMessage; - }; - - /** - * get hexadecimal hash of string with specified algorithm - * @name hashString - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @param {String} alg hash algorithm name - * @return {String} hexadecimal string of hash value - * @since 1.1.1 - */ - this.hashString = function(s, alg) { - var md = new KJUR.crypto.MessageDigest({'alg': alg}); - return md.digestString(s); - }; - - /** - * get hexadecimal hash of hexadecimal string with specified algorithm - * @name hashHex - * @memberOf KJUR.crypto.Util - * @function - * @param {String} sHex input hexadecimal string to be hashed - * @param {String} alg hash algorithm name - * @return {String} hexadecimal string of hash value - * @since 1.1.1 - */ - this.hashHex = function(sHex, alg) { - var md = new KJUR.crypto.MessageDigest({'alg': alg}); - return md.digestHex(sHex); - }; - - /** - * get hexadecimal SHA1 hash of string - * @name sha1 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.sha1 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha1', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - /** - * get hexadecimal SHA256 hash of string - * @name sha256 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.sha256 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha256', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - this.sha256Hex = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha256', 'prov':'cryptojs'}); - return md.digestHex(s); - }; - - /** - * get hexadecimal SHA512 hash of string - * @name sha512 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.sha512 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha512', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - this.sha512Hex = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha512', 'prov':'cryptojs'}); - return md.digestHex(s); - }; - - /** - * get hexadecimal MD5 hash of string - * @name md5 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.md5 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'md5', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - /** - * get hexadecimal RIPEMD160 hash of string - * @name ripemd160 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.ripemd160 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'ripemd160', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - /* - * @since 1.1.2 - */ - this.getCryptoJSMDByName = function(s) { - - }; -}; - -/** - * MessageDigest class which is very similar to java.security.MessageDigest class - * @name KJUR.crypto.MessageDigest - * @class MessageDigest class which is very similar to java.security.MessageDigest class - * @param {Array} params parameters for constructor - * @description - *
- * Currently this supports following algorithm and providers combination: - *
    - *
  • md5 - cryptojs
  • - *
  • sha1 - cryptojs
  • - *
  • sha224 - cryptojs
  • - *
  • sha256 - cryptojs
  • - *
  • sha384 - cryptojs
  • - *
  • sha512 - cryptojs
  • - *
  • ripemd160 - cryptojs
  • - *
  • sha256 - sjcl (NEW from crypto.js 1.0.4)
  • - *
- * @example - * // CryptoJS provider sample - * <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/core.js"></script> - * <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/sha1.js"></script> - * <script src="crypto-1.0.js"></script> - * var md = new KJUR.crypto.MessageDigest({alg: "sha1", prov: "cryptojs"}); - * md.updateString('aaa') - * var mdHex = md.digest() - * - * // SJCL(Stanford JavaScript Crypto Library) provider sample - * <script src="http://bitwiseshiftleft.github.io/sjcl/sjcl.js"></script> - * <script src="crypto-1.0.js"></script> - * var md = new KJUR.crypto.MessageDigest({alg: "sha256", prov: "sjcl"}); // sjcl supports sha256 only - * md.updateString('aaa') - * var mdHex = md.digest() - */ -KJUR.crypto.MessageDigest = function(params) { - var md = null; - var algName = null; - var provName = null; - - /** - * set hash algorithm and provider - * @name setAlgAndProvider - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} alg hash algorithm name - * @param {String} prov provider name - * @description - * @example - * // for SHA1 - * md.setAlgAndProvider('sha1', 'cryptojs'); - * // for RIPEMD160 - * md.setAlgAndProvider('ripemd160', 'cryptojs'); - */ - this.setAlgAndProvider = function(alg, prov) { - if (alg != null && prov === undefined) prov = KJUR.crypto.Util.DEFAULTPROVIDER[alg]; - - // for cryptojs - if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(alg) != -1 && - prov == 'cryptojs') { - try { - this.md = eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[alg]).create(); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail alg=" + alg + "/" + ex; - } - this.updateString = function(str) { - this.md.update(str); - }; - this.updateHex = function(hex) { - var wHex = CryptoJS.enc.Hex.parse(hex); - this.md.update(wHex); - }; - this.digest = function() { - var hash = this.md.finalize(); - return hash.toString(CryptoJS.enc.Hex); - }; - this.digestString = function(str) { - this.updateString(str); - return this.digest(); - }; - this.digestHex = function(hex) { - this.updateHex(hex); - return this.digest(); - }; - } - if (':sha256:'.indexOf(alg) != -1 && - prov == 'sjcl') { - try { - this.md = new sjcl.hash.sha256(); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail alg=" + alg + "/" + ex; - } - this.updateString = function(str) { - this.md.update(str); - }; - this.updateHex = function(hex) { - var baHex = sjcl.codec.hex.toBits(hex); - this.md.update(baHex); - }; - this.digest = function() { - var hash = this.md.finalize(); - return sjcl.codec.hex.fromBits(hash); - }; - this.digestString = function(str) { - this.updateString(str); - return this.digest(); - }; - this.digestHex = function(hex) { - this.updateHex(hex); - return this.digest(); - }; - } - }; - - /** - * update digest by specified string - * @name updateString - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} str string to update - * @description - * @example - * md.updateString('New York'); - */ - this.updateString = function(str) { - throw "updateString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * update digest by specified hexadecimal string - * @name updateHex - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} hex hexadecimal string to update - * @description - * @example - * md.updateHex('0afe36'); - */ - this.updateHex = function(hex) { - throw "updateHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * completes hash calculation and returns hash result - * @name digest - * @memberOf KJUR.crypto.MessageDigest - * @function - * @description - * @example - * md.digest() - */ - this.digest = function() { - throw "digest() not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * performs final update on the digest using string, then completes the digest computation - * @name digestString - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} str string to final update - * @description - * @example - * md.digestString('aaa') - */ - this.digestString = function(str) { - throw "digestString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * performs final update on the digest using hexadecimal string, then completes the digest computation - * @name digestHex - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} hex hexadecimal string to final update - * @description - * @example - * md.digestHex('0f2abd') - */ - this.digestHex = function(hex) { - throw "digestHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - if (params !== undefined) { - if (params['alg'] !== undefined) { - this.algName = params['alg']; - if (params['prov'] === undefined) - this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]; - this.setAlgAndProvider(this.algName, this.provName); - } - } -}; - -/** - * Mac(Message Authentication Code) class which is very similar to java.security.Mac class - * @name KJUR.crypto.Mac - * @class Mac class which is very similar to java.security.Mac class - * @param {Array} params parameters for constructor - * @description - *
- * Currently this supports following algorithm and providers combination: - *
    - *
  • hmacmd5 - cryptojs
  • - *
  • hmacsha1 - cryptojs
  • - *
  • hmacsha224 - cryptojs
  • - *
  • hmacsha256 - cryptojs
  • - *
  • hmacsha384 - cryptojs
  • - *
  • hmacsha512 - cryptojs
  • - *
- * NOTE: HmacSHA224 and HmacSHA384 issue was fixed since jsrsasign 4.1.4. - * Please use 'ext/cryptojs-312-core-fix*.js' instead of 'core.js' of original CryptoJS - * to avoid those issue. - * @example - * var mac = new KJUR.crypto.Mac({alg: "HmacSHA1", prov: "cryptojs", "pass": "pass"}); - * mac.updateString('aaa') - * var macHex = md.doFinal() - */ -KJUR.crypto.Mac = function(params) { - var mac = null; - var pass = null; - var algName = null; - var provName = null; - var algProv = null; - - this.setAlgAndProvider = function(alg, prov) { - if (alg == null) alg = "hmacsha1"; - - alg = alg.toLowerCase(); - if (alg.substr(0, 4) != "hmac") { - throw "setAlgAndProvider unsupported HMAC alg: " + alg; - } - - if (prov === undefined) prov = KJUR.crypto.Util.DEFAULTPROVIDER[alg]; - this.algProv = alg + "/" + prov; - - var hashAlg = alg.substr(4); - - // for cryptojs - if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(hashAlg) != -1 && - prov == 'cryptojs') { - try { - var mdObj = eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[hashAlg]); - this.mac = CryptoJS.algo.HMAC.create(mdObj, this.pass); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail hashAlg=" + hashAlg + "/" + ex; - } - this.updateString = function(str) { - this.mac.update(str); - }; - this.updateHex = function(hex) { - var wHex = CryptoJS.enc.Hex.parse(hex); - this.mac.update(wHex); - }; - this.doFinal = function() { - var hash = this.mac.finalize(); - return hash.toString(CryptoJS.enc.Hex); - }; - this.doFinalString = function(str) { - this.updateString(str); - return this.doFinal(); - }; - this.doFinalHex = function(hex) { - this.updateHex(hex); - return this.doFinal(); - }; - } - }; - - /** - * update digest by specified string - * @name updateString - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} str string to update - * @description - * @example - * md.updateString('New York'); - */ - this.updateString = function(str) { - throw "updateString(str) not supported for this alg/prov: " + this.algProv; - }; - - /** - * update digest by specified hexadecimal string - * @name updateHex - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} hex hexadecimal string to update - * @description - * @example - * md.updateHex('0afe36'); - */ - this.updateHex = function(hex) { - throw "updateHex(hex) not supported for this alg/prov: " + this.algProv; - }; - - /** - * completes hash calculation and returns hash result - * @name doFinal - * @memberOf KJUR.crypto.Mac - * @function - * @description - * @example - * md.digest() - */ - this.doFinal = function() { - throw "digest() not supported for this alg/prov: " + this.algProv; - }; - - /** - * performs final update on the digest using string, then completes the digest computation - * @name doFinalString - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} str string to final update - * @description - * @example - * md.digestString('aaa') - */ - this.doFinalString = function(str) { - throw "digestString(str) not supported for this alg/prov: " + this.algProv; - }; - - /** - * performs final update on the digest using hexadecimal string, - * then completes the digest computation - * @name doFinalHex - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} hex hexadecimal string to final update - * @description - * @example - * md.digestHex('0f2abd') - */ - this.doFinalHex = function(hex) { - throw "digestHex(hex) not supported for this alg/prov: " + this.algProv; - }; - - if (params !== undefined) { - if (params['pass'] !== undefined) { - this.pass = params['pass']; - } - if (params['alg'] !== undefined) { - this.algName = params['alg']; - if (params['prov'] === undefined) - this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]; - this.setAlgAndProvider(this.algName, this.provName); - } - } -}; - -/** - * Signature class which is very similar to java.security.Signature class - * @name KJUR.crypto.Signature - * @class Signature class which is very similar to java.security.Signature class - * @param {Array} params parameters for constructor - * @property {String} state Current state of this signature object whether 'SIGN', 'VERIFY' or null - * @description - *
- * As for params of constructor's argument, it can be specify following attributes: - *
    - *
  • alg - signature algorithm name (ex. {MD5,SHA1,SHA224,SHA256,SHA384,SHA512,RIPEMD160}with{RSA,ECDSA,DSA})
  • - *
  • provider - currently 'cryptojs/jsrsa' only
  • - *
- *

SUPPORTED ALGORITHMS AND PROVIDERS

- * This Signature class supports following signature algorithm and provider names: - *
    - *
  • MD5withRSA - cryptojs/jsrsa
  • - *
  • SHA1withRSA - cryptojs/jsrsa
  • - *
  • SHA224withRSA - cryptojs/jsrsa
  • - *
  • SHA256withRSA - cryptojs/jsrsa
  • - *
  • SHA384withRSA - cryptojs/jsrsa
  • - *
  • SHA512withRSA - cryptojs/jsrsa
  • - *
  • RIPEMD160withRSA - cryptojs/jsrsa
  • - *
  • MD5withECDSA - cryptojs/jsrsa
  • - *
  • SHA1withECDSA - cryptojs/jsrsa
  • - *
  • SHA224withECDSA - cryptojs/jsrsa
  • - *
  • SHA256withECDSA - cryptojs/jsrsa
  • - *
  • SHA384withECDSA - cryptojs/jsrsa
  • - *
  • SHA512withECDSA - cryptojs/jsrsa
  • - *
  • RIPEMD160withECDSA - cryptojs/jsrsa
  • - *
  • MD5withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA1withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA224withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA256withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA384withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA512withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • RIPEMD160withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA1withDSA - cryptojs/jsrsa
  • - *
  • SHA224withDSA - cryptojs/jsrsa
  • - *
  • SHA256withDSA - cryptojs/jsrsa
  • - *
- * Here are supported elliptic cryptographic curve names and their aliases for ECDSA: - *
    - *
  • secp256k1
  • - *
  • secp256r1, NIST P-256, P-256, prime256v1
  • - *
  • secp384r1, NIST P-384, P-384
  • - *
- * NOTE1: DSA signing algorithm is also supported since crypto 1.1.5. - *

EXAMPLES

- * @example - * // RSA signature generation - * var sig = new KJUR.crypto.Signature({"alg": "SHA1withRSA"}); - * sig.init(prvKeyPEM); - * sig.updateString('aaa'); - * var hSigVal = sig.sign(); - * - * // DSA signature validation - * var sig2 = new KJUR.crypto.Signature({"alg": "SHA1withDSA"}); - * sig2.init(certPEM); - * sig.updateString('aaa'); - * var isValid = sig2.verify(hSigVal); - * - * // ECDSA signing - * var sig = new KJUR.crypto.Signature({'alg':'SHA1withECDSA'}); - * sig.init(prvKeyPEM); - * sig.updateString('aaa'); - * var sigValueHex = sig.sign(); - * - * // ECDSA verifying - * var sig2 = new KJUR.crypto.Signature({'alg':'SHA1withECDSA'}); - * sig.init(certPEM); - * sig.updateString('aaa'); - * var isValid = sig.verify(sigValueHex); - */ -KJUR.crypto.Signature = function(params) { - var prvKey = null; // RSAKey/KJUR.crypto.{ECDSA,DSA} object for signing - var pubKey = null; // RSAKey/KJUR.crypto.{ECDSA,DSA} object for verifying - - var md = null; // KJUR.crypto.MessageDigest object - var sig = null; - var algName = null; - var provName = null; - var algProvName = null; - var mdAlgName = null; - var pubkeyAlgName = null; // rsa,ecdsa,rsaandmgf1(=rsapss) - var state = null; - var pssSaltLen = -1; - var initParams = null; - - var sHashHex = null; // hex hash value for hex - var hDigestInfo = null; - var hPaddedDigestInfo = null; - var hSign = null; - - this._setAlgNames = function() { - if (this.algName.match(/^(.+)with(.+)$/)) { - this.mdAlgName = RegExp.$1.toLowerCase(); - this.pubkeyAlgName = RegExp.$2.toLowerCase(); - } - }; - - this._zeroPaddingOfSignature = function(hex, bitLength) { - var s = ""; - var nZero = bitLength / 4 - hex.length; - for (var i = 0; i < nZero; i++) { - s = s + "0"; - } - return s + hex; - }; - - /** - * set signature algorithm and provider - * @name setAlgAndProvider - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} alg signature algorithm name - * @param {String} prov provider name - * @description - * @example - * md.setAlgAndProvider('SHA1withRSA', 'cryptojs/jsrsa'); - */ - this.setAlgAndProvider = function(alg, prov) { - this._setAlgNames(); - if (prov != 'cryptojs/jsrsa') - throw "provider not supported: " + prov; - - if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(this.mdAlgName) != -1) { - try { - this.md = new KJUR.crypto.MessageDigest({'alg':this.mdAlgName}); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail alg=" + - this.mdAlgName + "/" + ex; - } - - this.init = function(keyparam, pass) { - var keyObj = null; - try { - if (pass === undefined) { - keyObj = KEYUTIL.getKey(keyparam); - } else { - keyObj = KEYUTIL.getKey(keyparam, pass); - } - } catch (ex) { - throw "init failed:" + ex; - } - - if (keyObj.isPrivate === true) { - this.prvKey = keyObj; - this.state = "SIGN"; - } else if (keyObj.isPublic === true) { - this.pubKey = keyObj; - this.state = "VERIFY"; - } else { - throw "init failed.:" + keyObj; - } - }; - - this.initSign = function(params) { - if (typeof params['ecprvhex'] == 'string' && - typeof params['eccurvename'] == 'string') { - this.ecprvhex = params['ecprvhex']; - this.eccurvename = params['eccurvename']; - } else { - this.prvKey = params; - } - this.state = "SIGN"; - }; - - this.initVerifyByPublicKey = function(params) { - if (typeof params['ecpubhex'] == 'string' && - typeof params['eccurvename'] == 'string') { - this.ecpubhex = params['ecpubhex']; - this.eccurvename = params['eccurvename']; - } else if (params instanceof KJUR.crypto.ECDSA) { - this.pubKey = params; - } else if (params instanceof RSAKey) { - this.pubKey = params; - } - this.state = "VERIFY"; - }; - - this.initVerifyByCertificatePEM = function(certPEM) { - var x509 = new X509(); - x509.readCertPEM(certPEM); - this.pubKey = x509.subjectPublicKeyRSA; - this.state = "VERIFY"; - }; - - this.updateString = function(str) { - this.md.updateString(str); - }; - this.updateHex = function(hex) { - this.md.updateHex(hex); - }; - - this.sign = function() { - this.sHashHex = this.md.digest(); - if (typeof this.ecprvhex != "undefined" && - typeof this.eccurvename != "undefined") { - var ec = new KJUR.crypto.ECDSA({'curve': this.eccurvename}); - this.hSign = ec.signHex(this.sHashHex, this.ecprvhex); - } else if (this.pubkeyAlgName == "rsaandmgf1") { - this.hSign = this.prvKey.signWithMessageHashPSS(this.sHashHex, - this.mdAlgName, - this.pssSaltLen); - } else if (this.pubkeyAlgName == "rsa") { - this.hSign = this.prvKey.signWithMessageHash(this.sHashHex, - this.mdAlgName); - } else if (this.prvKey instanceof KJUR.crypto.ECDSA) { - this.hSign = this.prvKey.signWithMessageHash(this.sHashHex); - } else if (this.prvKey instanceof KJUR.crypto.DSA) { - this.hSign = this.prvKey.signWithMessageHash(this.sHashHex); - } else { - throw "Signature: unsupported public key alg: " + this.pubkeyAlgName; - } - return this.hSign; - }; - this.signString = function(str) { - this.updateString(str); - return this.sign(); - }; - this.signHex = function(hex) { - this.updateHex(hex); - return this.sign(); - }; - this.verify = function(hSigVal) { - this.sHashHex = this.md.digest(); - if (typeof this.ecpubhex != "undefined" && - typeof this.eccurvename != "undefined") { - var ec = new KJUR.crypto.ECDSA({curve: this.eccurvename}); - return ec.verifyHex(this.sHashHex, hSigVal, this.ecpubhex); - } else if (this.pubkeyAlgName == "rsaandmgf1") { - return this.pubKey.verifyWithMessageHashPSS(this.sHashHex, hSigVal, - this.mdAlgName, - this.pssSaltLen); - } else if (this.pubkeyAlgName == "rsa") { - return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal); - } else if (this.pubKey instanceof KJUR.crypto.ECDSA) { - return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal); - } else if (this.pubKey instanceof KJUR.crypto.DSA) { - return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal); - } else { - throw "Signature: unsupported public key alg: " + this.pubkeyAlgName; - } - }; - } - }; - - /** - * Initialize this object for signing or verifying depends on key - * @name init - * @memberOf KJUR.crypto.Signature - * @function - * @param {Object} key specifying public or private key as plain/encrypted PKCS#5/8 PEM file, certificate PEM or {@link RSAKey}, {@link KJUR.crypto.DSA} or {@link KJUR.crypto.ECDSA} object - * @param {String} pass (OPTION) passcode for encrypted private key - * @since crypto 1.1.3 - * @description - * This method is very useful initialize method for Signature class since - * you just specify key then this method will automatically initialize it - * using {@link KEYUTIL.getKey} method. - * As for 'key', following argument type are supported: - *
signing
- *
    - *
  • PEM formatted PKCS#8 encrypted RSA/ECDSA private key concluding "BEGIN ENCRYPTED PRIVATE KEY"
  • - *
  • PEM formatted PKCS#5 encrypted RSA/DSA private key concluding "BEGIN RSA/DSA PRIVATE KEY" and ",ENCRYPTED"
  • - *
  • PEM formatted PKCS#8 plain RSA/ECDSA private key concluding "BEGIN PRIVATE KEY"
  • - *
  • PEM formatted PKCS#5 plain RSA/DSA private key concluding "BEGIN RSA/DSA PRIVATE KEY" without ",ENCRYPTED"
  • - *
  • RSAKey object of private key
  • - *
  • KJUR.crypto.ECDSA object of private key
  • - *
  • KJUR.crypto.DSA object of private key
  • - *
- *
verification
- *
    - *
  • PEM formatted PKCS#8 RSA/EC/DSA public key concluding "BEGIN PUBLIC KEY"
  • - *
  • PEM formatted X.509 certificate with RSA/EC/DSA public key concluding - * "BEGIN CERTIFICATE", "BEGIN X509 CERTIFICATE" or "BEGIN TRUSTED CERTIFICATE".
  • - *
  • RSAKey object of public key
  • - *
  • KJUR.crypto.ECDSA object of public key
  • - *
  • KJUR.crypto.DSA object of public key
  • - *
- * @example - * sig.init(sCertPEM) - */ - this.init = function(key, pass) { - throw "init(key, pass) not supported for this alg:prov=" + - this.algProvName; - }; - - /** - * Initialize this object for verifying with a public key - * @name initVerifyByPublicKey - * @memberOf KJUR.crypto.Signature - * @function - * @param {Object} param RSAKey object of public key or associative array for ECDSA - * @since 1.0.2 - * @deprecated from crypto 1.1.5. please use init() method instead. - * @description - * Public key information will be provided as 'param' parameter and the value will be - * following: - *
    - *
  • {@link RSAKey} object for RSA verification
  • - *
  • associative array for ECDSA verification - * (ex. {'ecpubhex': '041f..', 'eccurvename': 'secp256r1'}) - *
  • - *
- * @example - * sig.initVerifyByPublicKey(rsaPrvKey) - */ - this.initVerifyByPublicKey = function(rsaPubKey) { - throw "initVerifyByPublicKey(rsaPubKeyy) not supported for this alg:prov=" + - this.algProvName; - }; - - /** - * Initialize this object for verifying with a certficate - * @name initVerifyByCertificatePEM - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} certPEM PEM formatted string of certificate - * @since 1.0.2 - * @deprecated from crypto 1.1.5. please use init() method instead. - * @description - * @example - * sig.initVerifyByCertificatePEM(certPEM) - */ - this.initVerifyByCertificatePEM = function(certPEM) { - throw "initVerifyByCertificatePEM(certPEM) not supported for this alg:prov=" + - this.algProvName; - }; - - /** - * Initialize this object for signing - * @name initSign - * @memberOf KJUR.crypto.Signature - * @function - * @param {Object} param RSAKey object of public key or associative array for ECDSA - * @deprecated from crypto 1.1.5. please use init() method instead. - * @description - * Private key information will be provided as 'param' parameter and the value will be - * following: - *
    - *
  • {@link RSAKey} object for RSA signing
  • - *
  • associative array for ECDSA signing - * (ex. {'ecprvhex': '1d3f..', 'eccurvename': 'secp256r1'})
  • - *
- * @example - * sig.initSign(prvKey) - */ - this.initSign = function(prvKey) { - throw "initSign(prvKey) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * Updates the data to be signed or verified by a string - * @name updateString - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} str string to use for the update - * @description - * @example - * sig.updateString('aaa') - */ - this.updateString = function(str) { - throw "updateString(str) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * Updates the data to be signed or verified by a hexadecimal string - * @name updateHex - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} hex hexadecimal string to use for the update - * @description - * @example - * sig.updateHex('1f2f3f') - */ - this.updateHex = function(hex) { - throw "updateHex(hex) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * Returns the signature bytes of all data updates as a hexadecimal string - * @name sign - * @memberOf KJUR.crypto.Signature - * @function - * @return the signature bytes as a hexadecimal string - * @description - * @example - * var hSigValue = sig.sign() - */ - this.sign = function() { - throw "sign() not supported for this alg:prov=" + this.algProvName; - }; - - /** - * performs final update on the sign using string, then returns the signature bytes of all data updates as a hexadecimal string - * @name signString - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} str string to final update - * @return the signature bytes of a hexadecimal string - * @description - * @example - * var hSigValue = sig.signString('aaa') - */ - this.signString = function(str) { - throw "digestString(str) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * performs final update on the sign using hexadecimal string, then returns the signature bytes of all data updates as a hexadecimal string - * @name signHex - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} hex hexadecimal string to final update - * @return the signature bytes of a hexadecimal string - * @description - * @example - * var hSigValue = sig.signHex('1fdc33') - */ - this.signHex = function(hex) { - throw "digestHex(hex) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * verifies the passed-in signature. - * @name verify - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} str string to final update - * @return {Boolean} true if the signature was verified, otherwise false - * @description - * @example - * var isValid = sig.verify('1fbcefdca4823a7(snip)') - */ - this.verify = function(hSigVal) { - throw "verify(hSigVal) not supported for this alg:prov=" + this.algProvName; - }; - - this.initParams = params; - - if (params !== undefined) { - if (params['alg'] !== undefined) { - this.algName = params['alg']; - if (params['prov'] === undefined) { - this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]; - } else { - this.provName = params['prov']; - } - this.algProvName = this.algName + ":" + this.provName; - this.setAlgAndProvider(this.algName, this.provName); - this._setAlgNames(); - } - - if (params['psssaltlen'] !== undefined) this.pssSaltLen = params['psssaltlen']; - - if (params['prvkeypem'] !== undefined) { - if (params['prvkeypas'] !== undefined) { - throw "both prvkeypem and prvkeypas parameters not supported"; - } else { - try { - var prvKey = new RSAKey(); - prvKey.readPrivateKeyFromPEMString(params['prvkeypem']); - this.initSign(prvKey); - } catch (ex) { - throw "fatal error to load pem private key: " + ex; - } - } - } - } -}; - -/** - * static object for cryptographic function utilities - * @name KJUR.crypto.OID - * @class static object for cryptography related OIDs - * @property {Array} oidhex2name key value of hexadecimal OID and its name - * (ex. '2a8648ce3d030107' and 'secp256r1') - * @since crypto 1.1.3 - * @description - */ - - -KJUR.crypto.OID = new function() { - this.oidhex2name = { - '2a864886f70d010101': 'rsaEncryption', - '2a8648ce3d0201': 'ecPublicKey', - '2a8648ce380401': 'dsa', - '2a8648ce3d030107': 'secp256r1', - '2b8104001f': 'secp192k1', - '2b81040021': 'secp224r1', - '2b8104000a': 'secp256k1', - '2b81040023': 'secp521r1', - '2b81040022': 'secp384r1', - '2a8648ce380403': 'SHA1withDSA', // 1.2.840.10040.4.3 - '608648016503040301': 'SHA224withDSA', // 2.16.840.1.101.3.4.3.1 - '608648016503040302': 'SHA256withDSA', // 2.16.840.1.101.3.4.3.2 - }; -}; - -/*! base64x-1.1.3 (c) 2012-2014 Kenji Urushima | kjur.github.com/jsjws/license - */ -/* - * base64x.js - Base64url and supplementary functions for Tom Wu's base64.js library - * - * version: 1.1.3 (2014 May 25) - * - * Copyright (c) 2012-2014 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsjws/license/ - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - * - * DEPENDS ON: - * - base64.js - Tom Wu's Base64 library - */ - -/** - * Base64URL and supplementary functions for Tom Wu's base64.js library.
- * This class is just provide information about global functions - * defined in 'base64x.js'. The 'base64x.js' script file provides - * global functions for converting following data each other. - *
    - *
  • (ASCII) String
  • - *
  • UTF8 String including CJK, Latin and other characters
  • - *
  • byte array
  • - *
  • hexadecimal encoded String
  • - *
  • Full URIComponent encoded String (such like "%69%94")
  • - *
  • Base64 encoded String
  • - *
  • Base64URL encoded String
  • - *
- * All functions in 'base64x.js' are defined in {@link _global_} and not - * in this class. - * - * @class Base64URL and supplementary functions for Tom Wu's base64.js library - * @author Kenji Urushima - * @version 1.1 (07 May 2012) - * @requires base64.js - * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - */ -function Base64x() { -} - -// ==== string / byte array ================================ -/** - * convert a string to an array of character codes - * @param {String} s - * @return {Array of Numbers} - */ -function stoBA(s) { - var a = new Array(); - for (var i = 0; i < s.length; i++) { - a[i] = s.charCodeAt(i); - } - return a; -} - -/** - * convert an array of character codes to a string - * @param {Array of Numbers} a array of character codes - * @return {String} s - */ -function BAtos(a) { - var s = ""; - for (var i = 0; i < a.length; i++) { - s = s + String.fromCharCode(a[i]); - } - return s; -} - -// ==== byte array / hex ================================ -/** - * convert an array of bytes(Number) to hexadecimal string.
- * @param {Array of Numbers} a array of bytes - * @return {String} hexadecimal string - */ -function BAtohex(a) { - var s = ""; - for (var i = 0; i < a.length; i++) { - var hex1 = a[i].toString(16); - if (hex1.length == 1) hex1 = "0" + hex1; - s = s + hex1; - } - return s; -} - -// ==== string / hex ================================ -/** - * convert a ASCII string to a hexadecimal string of ASCII codes.
- * NOTE: This can't be used for non ASCII characters. - * @param {s} s ASCII string - * @return {String} hexadecimal string - */ -function stohex(s) { - return BAtohex(stoBA(s)); -} - -// ==== string / base64 ================================ -/** - * convert a ASCII string to a Base64 encoded string.
- * NOTE: This can't be used for non ASCII characters. - * @param {s} s ASCII string - * @return {String} Base64 encoded string - */ -function stob64(s) { - return hex2b64(stohex(s)); -} - -// ==== string / base64url ================================ -/** - * convert a ASCII string to a Base64URL encoded string.
- * NOTE: This can't be used for non ASCII characters. - * @param {s} s ASCII string - * @return {String} Base64URL encoded string - */ -function stob64u(s) { - return b64tob64u(hex2b64(stohex(s))); -} - -/** - * convert a Base64URL encoded string to a ASCII string.
- * NOTE: This can't be used for Base64URL encoded non ASCII characters. - * @param {s} s Base64URL encoded string - * @return {String} ASCII string - */ -function b64utos(s) { - return BAtos(b64toBA(b64utob64(s))); -} - -// ==== base64 / base64url ================================ -/** - * convert a Base64 encoded string to a Base64URL encoded string.
- * Example: "ab+c3f/==" → "ab-c3f_" - * @param {String} s Base64 encoded string - * @return {String} Base64URL encoded string - */ -function b64tob64u(s) { - s = s.replace(/\=/g, ""); - s = s.replace(/\+/g, "-"); - s = s.replace(/\//g, "_"); - return s; -} - -/** - * convert a Base64URL encoded string to a Base64 encoded string.
- * Example: "ab-c3f_" → "ab+c3f/==" - * @param {String} s Base64URL encoded string - * @return {String} Base64 encoded string - */ -function b64utob64(s) { - if (s.length % 4 == 2) s = s + "=="; - else if (s.length % 4 == 3) s = s + "="; - s = s.replace(/-/g, "+"); - s = s.replace(/_/g, "/"); - return s; -} - -// ==== hex / base64url ================================ -/** - * convert a hexadecimal string to a Base64URL encoded string.
- * @param {String} s hexadecimal string - * @return {String} Base64URL encoded string - */ -function hextob64u(s) { - return b64tob64u(hex2b64(s)); -} - -/** - * convert a Base64URL encoded string to a hexadecimal string.
- * @param {String} s Base64URL encoded string - * @return {String} hexadecimal string - */ -function b64utohex(s) { - return b64tohex(b64utob64(s)); -} - -var utf8tob64u, b64utoutf8; - -if (typeof Buffer === 'function') -{ - utf8tob64u = function (s) - { - return b64tob64u(new Buffer(s, 'utf8').toString('base64')); - }; - - b64utoutf8 = function (s) - { - return new Buffer(b64utob64(s), 'base64').toString('utf8'); - }; -} -else -{ -// ==== utf8 / base64url ================================ -/** - * convert a UTF-8 encoded string including CJK or Latin to a Base64URL encoded string.
- * @param {String} s UTF-8 encoded string - * @return {String} Base64URL encoded string - * @since 1.1 - */ - utf8tob64u = function (s) - { - return hextob64u(uricmptohex(encodeURIComponentAll(s))); - }; - -/** - * convert a Base64URL encoded string to a UTF-8 encoded string including CJK or Latin.
- * @param {String} s Base64URL encoded string - * @return {String} UTF-8 encoded string - * @since 1.1 - */ - b64utoutf8 = function (s) - { - return decodeURIComponent(hextouricmp(b64utohex(s))); - }; -} - -// ==== utf8 / base64url ================================ -/** - * convert a UTF-8 encoded string including CJK or Latin to a Base64 encoded string.
- * @param {String} s UTF-8 encoded string - * @return {String} Base64 encoded string - * @since 1.1.1 - */ -function utf8tob64(s) { - return hex2b64(uricmptohex(encodeURIComponentAll(s))); -} - -/** - * convert a Base64 encoded string to a UTF-8 encoded string including CJK or Latin.
- * @param {String} s Base64 encoded string - * @return {String} UTF-8 encoded string - * @since 1.1.1 - */ -function b64toutf8(s) { - return decodeURIComponent(hextouricmp(b64tohex(s))); -} - -// ==== utf8 / hex ================================ -/** - * convert a UTF-8 encoded string including CJK or Latin to a hexadecimal encoded string.
- * @param {String} s UTF-8 encoded string - * @return {String} hexadecimal encoded string - * @since 1.1.1 - */ -function utf8tohex(s) { - return uricmptohex(encodeURIComponentAll(s)); -} - -/** - * convert a hexadecimal encoded string to a UTF-8 encoded string including CJK or Latin.
- * Note that when input is improper hexadecimal string as UTF-8 string, this function returns - * 'null'. - * @param {String} s hexadecimal encoded string - * @return {String} UTF-8 encoded string or null - * @since 1.1.1 - */ -function hextoutf8(s) { - return decodeURIComponent(hextouricmp(s)); -} - -/** - * convert a hexadecimal encoded string to raw string including non printable characters.
- * @param {String} s hexadecimal encoded string - * @return {String} raw string - * @since 1.1.2 - * @example - * hextorstr("610061") → "a\x00a" - */ -function hextorstr(sHex) { - var s = ""; - for (var i = 0; i < sHex.length - 1; i += 2) { - s += String.fromCharCode(parseInt(sHex.substr(i, 2), 16)); - } - return s; -} - -/** - * convert a raw string including non printable characters to hexadecimal encoded string.
- * @param {String} s raw string - * @return {String} hexadecimal encoded string - * @since 1.1.2 - * @example - * rstrtohex("a\x00a") → "610061" - */ -function rstrtohex(s) { - var result = ""; - for (var i = 0; i < s.length; i++) { - result += ("0" + s.charCodeAt(i).toString(16)).slice(-2); - } - return result; -} - -// ==== hex / b64nl ======================================= - -/* - * since base64x 1.1.3 - */ -function hextob64(s) { - return hex2b64(s); -} - -/* - * since base64x 1.1.3 - */ -function hextob64nl(s) { - var b64 = hextob64(s); - var b64nl = b64.replace(/(.{64})/g, "$1\r\n"); - b64nl = b64nl.replace(/\r\n$/, ''); - return b64nl; -} - -/* - * since base64x 1.1.3 - */ -function b64nltohex(s) { - var b64 = s.replace(/[^0-9A-Za-z\/+=]*/g, ''); - var hex = b64tohex(b64); - return hex; -} - -// ==== URIComponent / hex ================================ -/** - * convert a URLComponent string such like "%67%68" to a hexadecimal string.
- * @param {String} s URIComponent string such like "%67%68" - * @return {String} hexadecimal string - * @since 1.1 - */ -function uricmptohex(s) { - return s.replace(/%/g, ""); -} - -/** - * convert a hexadecimal string to a URLComponent string such like "%67%68".
- * @param {String} s hexadecimal string - * @return {String} URIComponent string such like "%67%68" - * @since 1.1 - */ -function hextouricmp(s) { - return s.replace(/(..)/g, "%$1"); -} - -// ==== URIComponent ================================ -/** - * convert UTFa hexadecimal string to a URLComponent string such like "%67%68".
- * Note that these "0-9A-Za-z!'()*-._~" characters will not - * converted to "%xx" format by builtin 'encodeURIComponent()' function. - * However this 'encodeURIComponentAll()' function will convert - * all of characters into "%xx" format. - * @param {String} s hexadecimal string - * @return {String} URIComponent string such like "%67%68" - * @since 1.1 - */ -function encodeURIComponentAll(u8) { - var s = encodeURIComponent(u8); - var s2 = ""; - for (var i = 0; i < s.length; i++) { - if (s[i] == "%") { - s2 = s2 + s.substr(i, 3); - i = i + 2; - } else { - s2 = s2 + "%" + stohex(s[i]); - } - } - return s2; -} - -// ==== new lines ================================ -/** - * convert all DOS new line("\r\n") to UNIX new line("\n") in - * a String "s". - * @param {String} s string - * @return {String} converted string - */ -function newline_toUnix(s) { - s = s.replace(/\r\n/mg, "\n"); - return s; -} - -/** - * convert all UNIX new line("\r\n") to DOS new line("\n") in - * a String "s". - * @param {String} s string - * @return {String} converted string - */ -function newline_toDos(s) { - s = s.replace(/\r\n/mg, "\n"); - s = s.replace(/\n/mg, "\r\n"); - return s; -} - -/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval - */ -// This source code is free for use in the public domain. -// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - -// http://code.google.com/p/json-sans-eval/ - -/** - * Parses a string of well-formed JSON text. - * - * If the input is not well-formed, then behavior is undefined, but it is - * deterministic and is guaranteed not to modify any object other than its - * return value. - * - * This does not use `eval` so is less likely to have obscure security bugs than - * json2.js. - * It is optimized for speed, so is much faster than json_parse.js. - * - * This library should be used whenever security is a concern (when JSON may - * come from an untrusted source), speed is a concern, and erroring on malformed - * JSON is *not* a concern. - * - * Pros Cons - * +-----------------------+-----------------------+ - * json_sans_eval.js | Fast, secure | Not validating | - * +-----------------------+-----------------------+ - * json_parse.js | Validating, secure | Slow | - * +-----------------------+-----------------------+ - * json2.js | Fast, some validation | Potentially insecure | - * +-----------------------+-----------------------+ - * - * json2.js is very fast, but potentially insecure since it calls `eval` to - * parse JSON data, so an attacker might be able to supply strange JS that - * looks like JSON, but that executes arbitrary javascript. - * If you do have to use json2.js with untrusted data, make sure you keep - * your version of json2.js up to date so that you get patches as they're - * released. - * - * @param {string} json per RFC 4627 - * @param {function (this:Object, string, *):*} opt_reviver optional function - * that reworks JSON objects post-parse per Chapter 15.12 of EcmaScript3.1. - * If supplied, the function is called with a string key, and a value. - * The value is the property of 'this'. The reviver should return - * the value to use in its place. So if dates were serialized as - * {@code { "type": "Date", "time": 1234 }}, then a reviver might look like - * {@code - * function (key, value) { - * if (value && typeof value === 'object' && 'Date' === value.type) { - * return new Date(value.time); - * } else { - * return value; - * } - * }}. - * If the reviver returns {@code undefined} then the property named by key - * will be deleted from its container. - * {@code this} is bound to the object containing the specified property. - * @return {Object|Array} - * @author Mike Samuel - */ -var jsonParse = (function () { - var number - = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)'; - var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]' - + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))'; - var string = '(?:\"' + oneChar + '*\")'; - - // Will match a value in a well-formed JSON file. - // If the input is not well-formed, may match strangely, but not in an unsafe - // way. - // Since this only matches value tokens, it does not match whitespace, colons, - // or commas. - var jsonToken = new RegExp( - '(?:false|true|null|[\\{\\}\\[\\]]' - + '|' + number - + '|' + string - + ')', 'g'); - - // Matches escape sequences in a string literal - var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g'); - - // Decodes escape sequences in object literals - var escapes = { - '"': '"', - '/': '/', - '\\': '\\', - 'b': '\b', - 'f': '\f', - 'n': '\n', - 'r': '\r', - 't': '\t' - }; - function unescapeOne(_, ch, hex) { - return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16)); - } - - // A non-falsy value that coerces to the empty string when used as a key. - var EMPTY_STRING = new String(''); - var SLASH = '\\'; - - // Constructor to use based on an open token. - var firstTokenCtors = { '{': Object, '[': Array }; - - var hop = Object.hasOwnProperty; - - return function (json, opt_reviver) { - // Split into tokens - var toks = json.match(jsonToken); - // Construct the object to return - var result; - var tok = toks[0]; - var topLevelPrimitive = false; - if ('{' === tok) { - result = {}; - } else if ('[' === tok) { - result = []; - } else { - // The RFC only allows arrays or objects at the top level, but the JSON.parse - // defined by the EcmaScript 5 draft does allow strings, booleans, numbers, and null - // at the top level. - result = []; - topLevelPrimitive = true; - } - - // If undefined, the key in an object key/value record to use for the next - // value parsed. - var key; - // Loop over remaining tokens maintaining a stack of uncompleted objects and - // arrays. - var stack = [result]; - for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) { - tok = toks[i]; - - var cont; - switch (tok.charCodeAt(0)) { - default: // sign or digit - cont = stack[0]; - cont[key || cont.length] = +(tok); - key = void 0; - break; - case 0x22: // '"' - tok = tok.substring(1, tok.length - 1); - if (tok.indexOf(SLASH) !== -1) { - tok = tok.replace(escapeSequence, unescapeOne); - } - cont = stack[0]; - if (!key) { - if (cont instanceof Array) { - key = cont.length; - } else { - key = tok || EMPTY_STRING; // Use as key for next value seen. - break; - } - } - cont[key] = tok; - key = void 0; - break; - case 0x5b: // '[' - cont = stack[0]; - stack.unshift(cont[key || cont.length] = []); - key = void 0; - break; - case 0x5d: // ']' - stack.shift(); - break; - case 0x66: // 'f' - cont = stack[0]; - cont[key || cont.length] = false; - key = void 0; - break; - case 0x6e: // 'n' - cont = stack[0]; - cont[key || cont.length] = null; - key = void 0; - break; - case 0x74: // 't' - cont = stack[0]; - cont[key || cont.length] = true; - key = void 0; - break; - case 0x7b: // '{' - cont = stack[0]; - stack.unshift(cont[key || cont.length] = {}); - key = void 0; - break; - case 0x7d: // '}' - stack.shift(); - break; - } - } - // Fail if we've got an uncompleted object. - if (topLevelPrimitive) { - if (stack.length !== 1) { throw new Error(); } - result = result[0]; - } else { - if (stack.length) { throw new Error(); } - } - - if (opt_reviver) { - // Based on walk as implemented in http://www.json.org/json2.js - var walk = function (holder, key) { - var value = holder[key]; - if (value && typeof value === 'object') { - var toDelete = null; - for (var k in value) { - if (hop.call(value, k) && value !== holder) { - // Recurse to properties first. This has the effect of causing - // the reviver to be called on the object graph depth-first. - - // Since 'this' is bound to the holder of the property, the - // reviver can access sibling properties of k including ones - // that have not yet been revived. - - // The value returned by the reviver is used in place of the - // current value of property k. - // If it returns undefined then the property is deleted. - var v = walk(value, k); - if (v !== void 0) { - value[k] = v; - } else { - // Deleting properties inside the loop has vaguely defined - // semantics in ES3 and ES3.1. - if (!toDelete) { toDelete = []; } - toDelete.push(k); - } - } - } - if (toDelete) { - for (var i = toDelete.length; --i >= 0;) { - delete value[toDelete[i]]; - } - } - } - return opt_reviver.call(holder, key, value); - }; - result = walk({ '': result }, ''); - } - - return result; - }; -})(); - -/*! jws-3.0.2 (c) 2013 Kenji Urushima | kjur.github.com/jsjws/license - */ -/* - * jws.js - JSON Web Signature Class - * - * version: 3.0.2 (2013 Sep 24) - * - * Copyright (c) 2010-2013 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsjws/license/ - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - */ - -/** - * @fileOverview - * @name jws-3.0.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version 3.0.1 (2013-Sep-24) - * @since jsjws 1.0 - * @license MIT License - */ - -if (typeof KJUR == "undefined" || !KJUR) KJUR = {}; -if (typeof KJUR.jws == "undefined" || !KJUR.jws) KJUR.jws = {}; - -/** - * JSON Web Signature(JWS) class.
- * @name KJUR.jws.JWS - * @class JSON Web Signature(JWS) class - * @property {Dictionary} parsedJWS This property is set after JWS signature verification.
- * Following "parsedJWS_*" properties can be accessed as "parsedJWS.*" because of - * JsDoc restriction. - * @property {String} parsedJWS_headB64U string of Encrypted JWS Header - * @property {String} parsedJWS_payloadB64U string of Encrypted JWS Payload - * @property {String} parsedJWS_sigvalB64U string of Encrypted JWS signature value - * @property {String} parsedJWS_si string of Signature Input - * @property {String} parsedJWS_sigvalH hexadecimal string of JWS signature value - * @property {String} parsedJWS_sigvalBI BigInteger(defined in jsbn.js) object of JWS signature value - * @property {String} parsedJWS_headS string of decoded JWS Header - * @property {String} parsedJWS_headS string of decoded JWS Payload - * @requires base64x.js, json-sans-eval.js and jsrsasign library - * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - * @see IETF I-D JSON Web Algorithms (JWA) - * @since jsjws 1.0 - * @description - *

Supported Algorithms

- * Here is supported algorithm names for {@link KJUR.jws.JWS.sign} and {@link KJUR.jws.JWS.verify} - * methods. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
alg valuespec requirementjsjws support
HS256REQUIREDSUPPORTED
HS384OPTIONALSUPPORTED
HS512OPTIONALSUPPORTED
RS256RECOMMENDEDSUPPORTED
RS384OPTIONALSUPPORTED
RS512OPTIONALSUPPORTED
ES256RECOMMENDED+SUPPORTED
ES384OPTIONALSUPPORTED
ES512OPTIONAL-
PS256OPTIONALSUPPORTED
PS384OPTIONALSUPPORTED
PS512OPTIONALSUPPORTED
noneREQUIREDSUPPORTED
- * NOTE: HS384 is supported since jsjws 3.0.2 with jsrsasign 4.1.4. - */ -KJUR.jws.JWS = function() { - - // === utility ============================================================= - - /** - * parse JWS string and set public property 'parsedJWS' dictionary.
- * @name parseJWS - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be parsed. - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @since jws 1.1 - */ - this.parseJWS = function(sJWS, sigValNotNeeded) { - if ((this.parsedJWS !== undefined) && - (sigValNotNeeded || (this.parsedJWS.sigvalH !== undefined))) { - return; - } - if (sJWS.match(/^([^.]+)\.([^.]+)\.([^.]+)$/) == null) { - throw "JWS signature is not a form of 'Head.Payload.SigValue'."; - } - var b6Head = RegExp.$1; - var b6Payload = RegExp.$2; - var b6SigVal = RegExp.$3; - var sSI = b6Head + "." + b6Payload; - this.parsedJWS = {}; - this.parsedJWS.headB64U = b6Head; - this.parsedJWS.payloadB64U = b6Payload; - this.parsedJWS.sigvalB64U = b6SigVal; - this.parsedJWS.si = sSI; - - if (!sigValNotNeeded) { - var hSigVal = b64utohex(b6SigVal); - var biSigVal = parseBigInt(hSigVal, 16); - this.parsedJWS.sigvalH = hSigVal; - this.parsedJWS.sigvalBI = biSigVal; - } - - var sHead = b64utoutf8(b6Head); - var sPayload = b64utoutf8(b6Payload); - this.parsedJWS.headS = sHead; - this.parsedJWS.payloadS = sPayload; - - if (!KJUR.jws.JWS.isSafeJSONString(sHead, this.parsedJWS, 'headP')) - throw "malformed JSON string for JWS Head: " + sHead; - }; - - // ==== JWS Validation ========================================================= - function _getSignatureInputByString(sHead, sPayload) { - return utf8tob64u(sHead) + "." + utf8tob64u(sPayload); - }; - - function _getHashBySignatureInput(sSignatureInput, sHashAlg) { - var hashfunc = function(s) { return KJUR.crypto.Util.hashString(s, sHashAlg); }; - if (hashfunc == null) throw "hash function not defined in jsrsasign: " + sHashAlg; - return hashfunc(sSignatureInput); - }; - - function _jws_verifySignature(sHead, sPayload, hSig, hN, hE) { - var sSignatureInput = _getSignatureInputByString(sHead, sPayload); - var biSig = parseBigInt(hSig, 16); - return _rsasign_verifySignatureWithArgs(sSignatureInput, biSig, hN, hE); - }; - - /** - * verify JWS signature with naked RSA public key.
- * This only supports "RS256" and "RS512" algorithm. - * @name verifyJWSByNE - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be verified - * @param {String} hN hexadecimal string for modulus of RSA public key - * @param {String} hE hexadecimal string for public exponent of RSA public key - * @return {String} returns 1 when JWS signature is valid, otherwise returns 0 - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.verify} - */ - this.verifyJWSByNE = function(sJWS, hN, hE) { - this.parseJWS(sJWS); - return _rsasign_verifySignatureWithArgs(this.parsedJWS.si, this.parsedJWS.sigvalBI, hN, hE); - }; - - /** - * verify JWS signature with RSA public key.
- * This only supports "RS256", "RS512", "PS256" and "PS512" algorithms. - * @name verifyJWSByKey - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be verified - * @param {RSAKey} key RSA public key - * @return {Boolean} returns true when JWS signature is valid, otherwise returns false - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.verify} - */ - this.verifyJWSByKey = function(sJWS, key) { - this.parseJWS(sJWS); - var hashAlg = _jws_getHashAlgFromParsedHead(this.parsedJWS.headP); - var isPSS = this.parsedJWS.headP['alg'].substr(0, 2) == "PS"; - - if (key.hashAndVerify) { - return key.hashAndVerify(hashAlg, - new Buffer(this.parsedJWS.si, 'utf8').toString('base64'), - b64utob64(this.parsedJWS.sigvalB64U), - 'base64', - isPSS); - } else if (isPSS) { - return key.verifyStringPSS(this.parsedJWS.si, - this.parsedJWS.sigvalH, hashAlg); - } else { - return key.verifyString(this.parsedJWS.si, - this.parsedJWS.sigvalH); - } - }; - - /** - * verify JWS signature by PEM formatted X.509 certificate.
- * This only supports "RS256" and "RS512" algorithm. - * @name verifyJWSByPemX509Cert - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be verified - * @param {String} sPemX509Cert string of PEM formatted X.509 certificate - * @return {String} returns 1 when JWS signature is valid, otherwise returns 0 - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @since 1.1 - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.verify} - */ - this.verifyJWSByPemX509Cert = function(sJWS, sPemX509Cert) { - this.parseJWS(sJWS); - var x509 = new X509(); - x509.readCertPEM(sPemX509Cert); - return x509.subjectPublicKeyRSA.verifyString(this.parsedJWS.si, this.parsedJWS.sigvalH); - }; - - // ==== JWS Generation ========================================================= - function _jws_getHashAlgFromParsedHead(head) { - var sigAlg = head["alg"]; - var hashAlg = ""; - - if (sigAlg != "RS256" && sigAlg != "RS512" && - sigAlg != "PS256" && sigAlg != "PS512") - throw "JWS signature algorithm not supported: " + sigAlg; - if (sigAlg.substr(2) == "256") hashAlg = "sha256"; - if (sigAlg.substr(2) == "512") hashAlg = "sha512"; - return hashAlg; - }; - - function _jws_getHashAlgFromHead(sHead) { - return _jws_getHashAlgFromParsedHead(jsonParse(sHead)); - }; - - function _jws_generateSignatureValueBySI_NED(sHead, sPayload, sSI, hN, hE, hD) { - var rsa = new RSAKey(); - rsa.setPrivate(hN, hE, hD); - - var hashAlg = _jws_getHashAlgFromHead(sHead); - var sigValue = rsa.signString(sSI, hashAlg); - return sigValue; - }; - - function _jws_generateSignatureValueBySI_Key(sHead, sPayload, sSI, key, head) { - var hashAlg = null; - if (typeof head == "undefined") { - hashAlg = _jws_getHashAlgFromHead(sHead); - } else { - hashAlg = _jws_getHashAlgFromParsedHead(head); - } - - var isPSS = head['alg'].substr(0, 2) == "PS"; - - if (key.hashAndSign) { - return b64tob64u(key.hashAndSign(hashAlg, sSI, 'binary', 'base64', isPSS)); - } else if (isPSS) { - return hextob64u(key.signStringPSS(sSI, hashAlg)); - } else { - return hextob64u(key.signString(sSI, hashAlg)); - } - }; - - function _jws_generateSignatureValueByNED(sHead, sPayload, hN, hE, hD) { - var sSI = _getSignatureInputByString(sHead, sPayload); - return _jws_generateSignatureValueBySI_NED(sHead, sPayload, sSI, hN, hE, hD); - }; - - /** - * generate JWS signature by Header, Payload and a naked RSA private key.
- * This only supports "RS256" and "RS512" algorithm. - * @name generateJWSByNED - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {String} hN hexadecimal string for modulus of RSA public key - * @param {String} hE hexadecimal string for public exponent of RSA public key - * @param {String} hD hexadecimal string for private exponent of RSA private key - * @return {String} JWS signature string - * @throws if sHead is a malformed JSON string. - * @throws if supported signature algorithm was not specified in JSON Header. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.sign} - */ - this.generateJWSByNED = function(sHead, sPayload, hN, hE, hD) { - if (!KJUR.jws.JWS.isSafeJSONString(sHead)) throw "JWS Head is not safe JSON string: " + sHead; - var sSI = _getSignatureInputByString(sHead, sPayload); - var hSigValue = _jws_generateSignatureValueBySI_NED(sHead, sPayload, sSI, hN, hE, hD); - var b64SigValue = hextob64u(hSigValue); - - this.parsedJWS = {}; - this.parsedJWS.headB64U = sSI.split(".")[0]; - this.parsedJWS.payloadB64U = sSI.split(".")[1]; - this.parsedJWS.sigvalB64U = b64SigValue; - - return sSI + "." + b64SigValue; - }; - - /** - * generate JWS signature by Header, Payload and a RSA private key.
- * This only supports "RS256", "RS512", "PS256" and "PS512" algorithms. - * @name generateJWSByKey - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {RSAKey} RSA private key - * @return {String} JWS signature string - * @throws if sHead is a malformed JSON string. - * @throws if supported signature algorithm was not specified in JSON Header. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.sign} - */ - this.generateJWSByKey = function(sHead, sPayload, key) { - var obj = {}; - if (!KJUR.jws.JWS.isSafeJSONString(sHead, obj, 'headP')) - throw "JWS Head is not safe JSON string: " + sHead; - var sSI = _getSignatureInputByString(sHead, sPayload); - var b64SigValue = _jws_generateSignatureValueBySI_Key(sHead, sPayload, sSI, key, obj.headP); - - this.parsedJWS = {}; - this.parsedJWS.headB64U = sSI.split(".")[0]; - this.parsedJWS.payloadB64U = sSI.split(".")[1]; - this.parsedJWS.sigvalB64U = b64SigValue; - - return sSI + "." + b64SigValue; - }; - - // === sign with PKCS#1 RSA private key ===================================================== - function _jws_generateSignatureValueBySI_PemPrvKey(sHead, sPayload, sSI, sPemPrvKey) { - var rsa = new RSAKey(); - rsa.readPrivateKeyFromPEMString(sPemPrvKey); - var hashAlg = _jws_getHashAlgFromHead(sHead); - var sigValue = rsa.signString(sSI, hashAlg); - return sigValue; - }; - - /** - * generate JWS signature by Header, Payload and a PEM formatted PKCS#1 RSA private key.
- * This only supports "RS256" and "RS512" algorithm. - * @name generateJWSByP1PrvKey - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {String} string for sPemPrvKey PEM formatted PKCS#1 RSA private key
- * Heading and trailing space characters in PEM key will be ignored. - * @return {String} JWS signature string - * @throws if sHead is a malformed JSON string. - * @throws if supported signature algorithm was not specified in JSON Header. - * @since 1.1 - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.sign} - */ - this.generateJWSByP1PrvKey = function(sHead, sPayload, sPemPrvKey) { - if (!KJUR.jws.JWS.isSafeJSONString(sHead)) throw "JWS Head is not safe JSON string: " + sHead; - var sSI = _getSignatureInputByString(sHead, sPayload); - var hSigValue = _jws_generateSignatureValueBySI_PemPrvKey(sHead, sPayload, sSI, sPemPrvKey); - var b64SigValue = hextob64u(hSigValue); - - this.parsedJWS = {}; - this.parsedJWS.headB64U = sSI.split(".")[0]; - this.parsedJWS.payloadB64U = sSI.split(".")[1]; - this.parsedJWS.sigvalB64U = b64SigValue; - - return sSI + "." + b64SigValue; - }; -}; - -// === major static method ======================================================== - -/** - * generate JWS signature by specified key
- * @name sign - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} alg JWS algorithm name to sign and force set to sHead or null - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {String} key string of private key or key object to sign - * @param {String} pass (OPTION)passcode to use encrypted private key - * @return {String} JWS signature string - * @since jws 3.0.0 - * @see jsrsasign KJUR.crypto.Signature method - * @see jsrsasign KJUR.crypto.Mac method - * @description - * This method supports following algorithms. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
alg valuespec requirementjsjws support
HS256REQUIREDSUPPORTED
HS384OPTIONAL-
HS512OPTIONALSUPPORTED
RS256RECOMMENDEDSUPPORTED
RS384OPTIONALSUPPORTED
RS512OPTIONALSUPPORTED
ES256RECOMMENDED+SUPPORTED
ES384OPTIONALSUPPORTED
ES512OPTIONAL-
PS256OPTIONALSUPPORTED
PS384OPTIONALSUPPORTED
PS512OPTIONALSUPPORTED
noneREQUIREDSUPPORTED
- *
- *
NOTE1: - *
salt length of RSAPSS signature is the same as the hash algorithm length - * because of IETF JOSE ML discussion. - *
NOTE2: - *
The reason of HS384 unsupport is - * CryptoJS HmacSHA384 bug. - *
- */ -KJUR.jws.JWS.sign = function(alg, sHeader, sPayload, key, pass) { - var ns1 = KJUR.jws.JWS; - - if (! ns1.isSafeJSONString(sHeader)) - throw "JWS Head is not safe JSON string: " + sHead; - - var pHeader = ns1.readSafeJSONString(sHeader); - - // 1. use alg if defined in sHeader - if ((alg == '' || alg == null) && - pHeader['alg'] !== undefined) { - alg = pHeader['alg']; - } - - // 2. set alg in sHeader if undefined - if ((alg != '' && alg != null) && - pHeader['alg'] === undefined) { - pHeader['alg'] = alg; - sHeader = JSON.stringify(pHeader); - } - - // 3. set signature algorithm like SHA1withRSA - var sigAlg = null; - if (ns1.jwsalg2sigalg[alg] === undefined) { - throw "unsupported alg name: " + alg; - } else { - sigAlg = ns1.jwsalg2sigalg[alg]; - } - - var uHeader = utf8tob64u(sHeader); - var uPayload = utf8tob64u(sPayload); - var uSignatureInput = uHeader + "." + uPayload - - // 4. sign - var hSig = ""; - if (sigAlg.substr(0, 4) == "Hmac") { - if (key === undefined) - throw "hexadecimal key shall be specified for HMAC"; - var mac = new KJUR.crypto.Mac({'alg': sigAlg, 'pass': hextorstr(key)}); - mac.updateString(uSignatureInput); - hSig = mac.doFinal(); - } else if (sigAlg.indexOf("withECDSA") != -1) { - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key, pass); - sig.updateString(uSignatureInput); - hASN1Sig = sig.sign(); - hSig = KJUR.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig); - } else if (sigAlg != "none") { - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key, pass); - sig.updateString(uSignatureInput); - hSig = sig.sign(); - } - - var uSig = hextob64u(hSig); - return uSignatureInput + "." + uSig; -}; - -/** - * verify JWS signature by specified key or certificate
- * @name verify - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} sJWS string of JWS signature to verify - * @param {String} key string of public key, certificate or key object to verify - * @return {Boolean} true if the signature is valid otherwise false - * @since jws 3.0.0 - * @see jsrsasign KJUR.crypto.Signature method - * @see jsrsasign KJUR.crypto.Mac method - */ -KJUR.jws.JWS.verify = function(sJWS, key) { - var jws = KJUR.jws.JWS; - var a = sJWS.split("."); - var uHeader = a[0]; - var uPayload = a[1]; - var uSignatureInput = uHeader + "." + uPayload; - var hSig = b64utohex(a[2]); - - var pHeader = jws.readSafeJSONString(b64utoutf8(a[0])); - var alg = null; - if (pHeader.alg === undefined) { - throw "algorithm not specified in header"; - } else { - alg = pHeader.alg; - } - - var sigAlg = null; - if (jws.jwsalg2sigalg[pHeader.alg] === undefined) { - throw "unsupported alg name: " + alg; - } else { - sigAlg = jws.jwsalg2sigalg[alg]; - } - - // x. verify - if (sigAlg == "none") { - return true; - } else if (sigAlg.substr(0, 4) == "Hmac") { - if (key === undefined) - throw "hexadecimal key shall be specified for HMAC"; - var mac = new KJUR.crypto.Mac({'alg': sigAlg, 'pass': hextorstr(key)}); - mac.updateString(uSignatureInput); - hSig2 = mac.doFinal(); - return hSig == hSig2; - } else if (sigAlg.indexOf("withECDSA") != -1) { - var hASN1Sig = null; - try { - hASN1Sig = KJUR.crypto.ECDSA.concatSigToASN1Sig(hSig); - } catch (ex) { - return false; - } - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key) - sig.updateString(uSignatureInput); - return sig.verify(hASN1Sig); - } else { - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key) - sig.updateString(uSignatureInput); - return sig.verify(hSig); - } -}; - -/* - * @since jws 3.0.0 - */ -KJUR.jws.JWS.jwsalg2sigalg = { - "HS256": "HmacSHA256", - //"HS384": "HmacSHA384", // unsupported because of CryptoJS bug - "HS512": "HmacSHA512", - "RS256": "SHA256withRSA", - "RS384": "SHA384withRSA", - "RS512": "SHA512withRSA", - "ES256": "SHA256withECDSA", - "ES384": "SHA384withECDSA", - //"ES512": "SHA512withECDSA", // unsupported because of jsrsasign's bug - "PS256": "SHA256withRSAandMGF1", - "PS384": "SHA384withRSAandMGF1", - "PS512": "SHA512withRSAandMGF1", - "none": "none", -}; - -// === utility static method ====================================================== - -/** - * check whether a String "s" is a safe JSON string or not.
- * If a String "s" is a malformed JSON string or an other object type - * this returns 0, otherwise this returns 1. - * @name isSafeJSONString - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} s JSON string - * @return {Number} 1 or 0 - */ -KJUR.jws.JWS.isSafeJSONString = function(s, h, p) { - var o = null; - try { - o = jsonParse(s); - if (typeof o != "object") return 0; - if (o.constructor === Array) return 0; - if (h) h[p] = o; - return 1; - } catch (ex) { - return 0; - } -}; - -/** - * read a String "s" as JSON object if it is safe.
- * If a String "s" is a malformed JSON string or not JSON string, - * this returns null, otherwise returns JSON object. - * @name readSafeJSONString - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} s JSON string - * @return {Object} JSON object or null - * @since 1.1.1 - */ -KJUR.jws.JWS.readSafeJSONString = function(s) { - var o = null; - try { - o = jsonParse(s); - if (typeof o != "object") return null; - if (o.constructor === Array) return null; - return o; - } catch (ex) { - return null; - } -}; - -/** - * get Encoed Signature Value from JWS string.
- * @name getEncodedSignatureValueFromJWS - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} sJWS JWS signature string to be verified - * @return {String} string of Encoded Signature Value - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - */ -KJUR.jws.JWS.getEncodedSignatureValueFromJWS = function(sJWS) { - if (sJWS.match(/^[^.]+\.[^.]+\.([^.]+)$/) == null) { - throw "JWS signature is not a form of 'Head.Payload.SigValue'."; - } - return RegExp.$1; -}; - -/** - * IntDate class for time representation for JSON Web Token(JWT) - * @class KJUR.jws.IntDate class - * @name KJUR.jws.IntDate - * @since jws 3.0.1 - * @description - * Utility class for IntDate which is integer representation of UNIX origin time - * used in JSON Web Token(JWT). - */ -KJUR.jws.IntDate = function() { -}; - -/** - * @name get - * @memberOf KJUR.jws.IntDate - * @function - * @static - * @param {String} s string of time representation - * @return {Integer} UNIX origin time in seconds for argument 's' - * @since jws 3.0.1 - * @throws "unsupported format: s" when malformed format - * @description - * This method will accept following representation of time. - *
    - *
  • now - current time
  • - *
  • now + 1hour - after 1 hour from now
  • - *
  • now + 1day - after 1 day from now
  • - *
  • now + 1month - after 30 days from now
  • - *
  • now + 1year - after 365 days from now
  • - *
  • YYYYmmDDHHMMSSZ - UTC time (ex. 20130828235959Z)
  • - *
  • number - UNIX origin time (seconds from 1970-01-01 00:00:00) (ex. 1377714748)
  • - *
- */ -KJUR.jws.IntDate.get = function(s) { - if (s == "now") { - return KJUR.jws.IntDate.getNow(); - } else if (s == "now + 1hour") { - return KJUR.jws.IntDate.getNow() + 60 * 60; - } else if (s == "now + 1day") { - return KJUR.jws.IntDate.getNow() + 60 * 60 * 24; - } else if (s == "now + 1month") { - return KJUR.jws.IntDate.getNow() + 60 * 60 * 24 * 30; - } else if (s == "now + 1year") { - return KJUR.jws.IntDate.getNow() + 60 * 60 * 24 * 365; - } else if (s.match(/Z$/)) { - return KJUR.jws.IntDate.getZulu(s); - } else if (s.match(/^[0-9]+$/)) { - return parseInt(s); - } - throw "unsupported format: " + s; -}; - -KJUR.jws.IntDate.getZulu = function(s) { - if (a = s.match(/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z/)) { - var year = parseInt(RegExp.$1); - var month = parseInt(RegExp.$2) - 1; - var day = parseInt(RegExp.$3); - var hour = parseInt(RegExp.$4); - var min = parseInt(RegExp.$5); - var sec = parseInt(RegExp.$6); - var d = new Date(Date.UTC(year, month, day, hour, min, sec)); - return ~~(d / 1000); - } - throw "unsupported format: " + s; -}; - -/* - * @since jws 3.0.1 - */ -KJUR.jws.IntDate.getNow = function() { - var d = ~~(new Date() / 1000); - return d; -}; - -/* - * @since jws 3.0.1 - */ -KJUR.jws.IntDate.intDate2UTCString = function(intDate) { - var d = new Date(intDate * 1000); - return d.toUTCString(); -}; - -/* - * @since jws 3.0.1 - */ -KJUR.jws.IntDate.intDate2Zulu = function(intDate) { - var d = new Date(intDate * 1000); - var year = ("0000" + d.getUTCFullYear()).slice(-4); - var mon = ("00" + (d.getUTCMonth() + 1)).slice(-2); - var day = ("00" + d.getUTCDate()).slice(-2); - var hour = ("00" + d.getUTCHours()).slice(-2); - var min = ("00" + d.getUTCMinutes()).slice(-2); - var sec = ("00" + d.getUTCSeconds()).slice(-2); - return year + mon + day + hour + min + sec + "Z"; -}; - -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 3.0.2 - */ - -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - var lib$es6$promise$asap$$customSchedulerFn; - - var lib$es6$promise$asap$$asap = function asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (lib$es6$promise$asap$$customSchedulerFn) { - lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); - } else { - lib$es6$promise$asap$$scheduleFlush(); - } - } - } - - function lib$es6$promise$asap$$setScheduler(scheduleFn) { - lib$es6$promise$asap$$customSchedulerFn = scheduleFn; - } - - function lib$es6$promise$asap$$setAsap(asapFn) { - lib$es6$promise$asap$$asap = asapFn; - } - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$asap(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; - lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; - lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$asap(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - - -/** - * @constructor - */ -function DefaultHttpRequest() { - - /** - * @name _promiseFactory - * @type DefaultPromiseFactory - */ - - /** - * @param {XMLHttpRequest} xhr - * @param {object.} headers - */ - function setHeaders(xhr, headers) { - var keys = Object.keys(headers); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = headers[key]; - - xhr.setRequestHeader(key, value); - } - } - - /** - * @param {string} url - * @param {{ headers: object. }} [config] - * @returns {Promise} - */ - this.getJSON = function (url, config) { - return _promiseFactory.create(function (resolve, reject) { - - try { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url); - xhr.responseType = "json"; - - if (config) { - if (config.headers) { - setHeaders(xhr, config.headers); - } - } - - xhr.onload = function () { - try { - if (xhr.status === 200) { - var response = ""; - // To support IE9 get the response from xhr.responseText not xhr.response - if (window.XDomainRequest) { - response = xhr.responseText; - } else { - response = xhr.response; - } - if (typeof response === "string") { - response = JSON.parse(response); - } - resolve(response); - } - else { - reject(Error(xhr.statusText + "(" + xhr.status + ")")); - } - } - catch (err) { - reject(err); - } - }; - - xhr.onerror = function () { - reject(Error("Network error")); - }; - - xhr.send(); - } - catch (err) { - return reject(err); - } - }); - }; -} - -_httpRequest = new DefaultHttpRequest(); - -/** - * @constructor - * @param {Promise} promise - */ -function DefaultPromise(promise) { - - /** - * @param {function(*):*} successCallback - * @param {function(*):*} errorCallback - * @returns {DefaultPromise} - */ - this.then = function (successCallback, errorCallback) { - var childPromise = promise.then(successCallback, errorCallback); - - return new DefaultPromise(childPromise); - }; - - /** - * - * @param {function(*):*} errorCallback - * @returns {DefaultPromise} - */ - this.catch = function (errorCallback) { - var childPromise = promise.catch(errorCallback); - - return new DefaultPromise(childPromise); - }; -} - -/** - * @constructor - */ -function DefaultPromiseFactory() { - - this.resolve = function (value) { - return new DefaultPromise(Promise.resolve(value)); - }; - - this.reject = function (reason) { - return new DefaultPromise(Promise.reject(reason)); - }; - - /** - * @param {function(resolve:function, reject:function)} callback - * @returns {DefaultPromise} - */ - this.create = function (callback) { - return new DefaultPromise(new Promise(callback)); - }; -} - -_promiseFactory = new DefaultPromiseFactory(); -/* - * Copyright 2015 Dominick Baier, Brock Allen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function log() { - //var param = [].join.call(arguments); - //console.log(param); -} - -function copy(obj, target) { - target = target || {}; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - target[key] = obj[key]; - } - } - return target; -} - -function rand() { - return ((Date.now() + Math.random()) * Math.random()).toString().replace(".", ""); -} - -function resolve(param) { - return _promiseFactory.resolve(param); -} - -function error(message) { - return _promiseFactory.reject(Error(message)); -} - -function parseOidcResult(queryString) { - log("parseOidcResult"); - - queryString = queryString || location.hash; - - var idx = queryString.lastIndexOf("#"); - if (idx >= 0) { - queryString = queryString.substr(idx + 1); - } - - var params = {}, - regex = /([^&=]+)=([^&]*)/g, - m; - - var counter = 0; - while (m = regex.exec(queryString)) { - params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); - if (counter++ > 50) { - return { - error: "Response exceeded expected number of parameters" - }; - } - } - - for (var prop in params) { - return params; - } -} - -function getJson(url, token) { - log("getJson", url); - - var config = {}; - - if (token) { - config.headers = {"Authorization": "Bearer " + token}; - } - - return _httpRequest.getJSON(url, config); -} - -function OidcClient(settings) { - this._settings = settings || {}; - - if (!this._settings.request_state_key) { - this._settings.request_state_key = "OidcClient.request_state"; - } - - if (!this._settings.request_state_store) { - this._settings.request_state_store = window.localStorage; - } - - if (typeof this._settings.load_user_profile === 'undefined') { - this._settings.load_user_profile = true; - } - - if (typeof this._settings.filter_protocol_claims === 'undefined') { - this._settings.filter_protocol_claims = true; - } - - if (this._settings.authority && this._settings.authority.indexOf('.well-known/openid-configuration') < 0) { - if (this._settings.authority[this._settings.authority.length - 1] !== '/') { - this._settings.authority += '/'; - } - this._settings.authority += '.well-known/openid-configuration'; - } - - if (!this._settings.response_type) { - this._settings.response_type = "id_token token"; - } - - Object.defineProperty(this, "isOidc", { - get: function () { - if (this._settings.response_type) { - var result = this._settings.response_type.split(/\s+/g).filter(function (item) { - return item === "id_token"; - }); - return !!(result[0]); - } - return false; - } - }); - - Object.defineProperty(this, "isOAuth", { - get: function () { - if (this._settings.response_type) { - var result = this._settings.response_type.split(/\s+/g).filter(function (item) { - return item === "token"; - }); - return !!(result[0]); - } - return false; - } - }); -} - -OidcClient.parseOidcResult = parseOidcResult; - -OidcClient.prototype.loadMetadataAsync = function () { - log("OidcClient.loadMetadataAsync"); - - var settings = this._settings; - - if (settings.metadata) { - return resolve(settings.metadata); - } - - if (!settings.authority) { - return error("No authority configured"); - } - - return getJson(settings.authority) - .then(function (metadata) { - settings.metadata = metadata; - return metadata; - }, function (err) { - return error("Failed to load metadata (" + err && err.message + ")"); - }); -}; - -OidcClient.prototype.loadX509SigningKeyAsync = function () { - log("OidcClient.loadX509SigningKeyAsync"); - - var settings = this._settings; - - function getKeyAsync(jwks) { - if (!jwks.keys || !jwks.keys.length) { - return error("Signing keys empty"); - } - - var key = jwks.keys[0]; - if (key.kty !== "RSA") { - return error("Signing key not RSA"); - } - - if (!key.x5c || !key.x5c.length) { - return error("RSA keys empty"); - } - - return resolve(key.x5c[0]); - } - - if (settings.jwks) { - return getKeyAsync(settings.jwks); - } - - return this.loadMetadataAsync().then(function (metadata) { - if (!metadata.jwks_uri) { - return error("Metadata does not contain jwks_uri"); - } - - return getJson(metadata.jwks_uri).then(function (jwks) { - settings.jwks = jwks; - return getKeyAsync(jwks); - }, function (err) { - return error("Failed to load signing keys (" + err && err.message + ")"); - }); - }); -}; - -OidcClient.prototype.loadUserProfile = function (access_token) { - log("OidcClient.loadUserProfile"); - - return this.loadMetadataAsync().then(function (metadata) { - - if (!metadata.userinfo_endpoint) { - return error("Metadata does not contain userinfo_endpoint"); - } - - return getJson(metadata.userinfo_endpoint, access_token); - }); -} - -OidcClient.prototype.loadAuthorizationEndpoint = function () { - log("OidcClient.loadAuthorizationEndpoint"); - - if (this._settings.authorization_endpoint) { - return resolve(this._settings.authorization_endpoint); - } - - if (!this._settings.authority) { - return error("No authorization_endpoint configured"); - } - - return this.loadMetadataAsync().then(function (metadata) { - if (!metadata.authorization_endpoint) { - return error("Metadata does not contain authorization_endpoint"); - } - - return metadata.authorization_endpoint; - }); -}; - -OidcClient.prototype.createTokenRequestAsync = function () { - log("OidcClient.createTokenRequestAsync"); - - var client = this; - var settings = client._settings; - - return client.loadAuthorizationEndpoint().then(function (authorization_endpoint) { - - var state = rand(); - var url = authorization_endpoint + "?state=" + encodeURIComponent(state); - - if (client.isOidc) { - var nonce = rand(); - url += "&nonce=" + encodeURIComponent(nonce); - } - - var required = ["client_id", "redirect_uri", "response_type", "scope"]; - required.forEach(function (key) { - var value = settings[key]; - if (value) { - url += "&" + key + "=" + encodeURIComponent(value); - } - }); - - var optional = ["prompt", "display", "max_age", "ui_locales", "id_token_hint", "login_hint", "acr_values"]; - optional.forEach(function (key) { - var value = settings[key]; - if (value) { - url += "&" + key + "=" + encodeURIComponent(value); - } - }); - - var request_state = { - oidc: client.isOidc, - oauth: client.isOAuth, - state: state - }; - - if (nonce) { - request_state["nonce"] = nonce; - } - - settings.request_state_store.setItem(settings.request_state_key, JSON.stringify(request_state)); - - return { - request_state: request_state, - url: url - }; - }); -} - -OidcClient.prototype.createLogoutRequestAsync = function (id_token_hint) { - log("OidcClient.createLogoutRequestAsync"); - - var settings = this._settings; - return this.loadMetadataAsync().then(function (metadata) { - if (!metadata.end_session_endpoint) { - return error("No end_session_endpoint in metadata"); - } - - var url = metadata.end_session_endpoint; - if (id_token_hint && settings.post_logout_redirect_uri) { - url += "?post_logout_redirect_uri=" + encodeURIComponent(settings.post_logout_redirect_uri); - url += "&id_token_hint=" + encodeURIComponent(id_token_hint); - } - return url; - }); -} - -OidcClient.prototype.validateIdTokenAsync = function (id_token, nonce, access_token) { - log("OidcClient.validateIdTokenAsync"); - - var client = this; - var settings = client._settings; - - return client.loadX509SigningKeyAsync().then(function (cert) { - - var jws = new KJUR.jws.JWS(); - if (jws.verifyJWSByPemX509Cert(id_token, cert)) { - var id_token_contents = JSON.parse(jws.parsedJWS.payloadS); - - if (nonce !== id_token_contents.nonce) { - return error("Invalid nonce"); - } - - return client.loadMetadataAsync().then(function (metadata) { - - if (id_token_contents.iss !== metadata.issuer) { - return error("Invalid issuer"); - } - - if (id_token_contents.aud !== settings.client_id) { - return error("Invalid audience"); - } - - var now = parseInt(Date.now() / 1000); - - // accept tokens issues up to 5 mins ago - var diff = now - id_token_contents.iat; - if (diff > (5 * 60)) { - return error("Token issued too long ago"); - } - - if (id_token_contents.exp < now) { - return error("Token expired"); - } - - if (access_token && settings.load_user_profile) { - // if we have an access token, then call user info endpoint - return client.loadUserProfile(access_token, id_token_contents).then(function (profile) { - return copy(profile, id_token_contents); - }); - } - else { - // no access token, so we have all our claims - return id_token_contents; - } - - }); - } - else { - return error("JWT failed to validate"); - } - - }); - -}; - -OidcClient.prototype.validateAccessTokenAsync = function (id_token_contents, access_token) { - log("OidcClient.validateAccessTokenAsync"); - - if (!id_token_contents.at_hash) { - return error("No at_hash in id_token"); - } - - var hash = KJUR.crypto.Util.sha256(access_token); - var left = hash.substr(0, hash.length / 2); - var left_b64u = hextob64u(left); - - if (left_b64u !== id_token_contents.at_hash) { - return error("at_hash failed to validate"); - } - - return resolve(); -}; - -OidcClient.prototype.validateIdTokenAndAccessTokenAsync = function (id_token, nonce, access_token) { - log("OidcClient.validateIdTokenAndAccessTokenAsync"); - - var client = this; - - return client.validateIdTokenAsync(id_token, nonce, access_token).then(function (id_token_contents) { - - return client.validateAccessTokenAsync(id_token_contents, access_token).then(function () { - - return id_token_contents; - - }); - - }); -} - -OidcClient.prototype.processResponseAsync = function (queryString) { - log("OidcClient.processResponseAsync"); - - var client = this; - var settings = client._settings; - - var request_state = settings.request_state_store.getItem(settings.request_state_key); - settings.request_state_store.removeItem(settings.request_state_key); - - if (!request_state) { - return error("No request state loaded"); - } - - request_state = JSON.parse(request_state); - if (!request_state) { - return error("No request state loaded"); - } - - if (!request_state.state) { - return error("No state loaded"); - } - - var result = parseOidcResult(queryString); - if (!result) { - return error("No OIDC response"); - } - - if (result.error) { - return error(result.error); - } - - if (result.state !== request_state.state) { - return error("Invalid state"); - } - - if (request_state.oidc) { - if (!result.id_token) { - return error("No identity token"); - } - - if (!request_state.nonce) { - return error("No nonce loaded"); - } - } - - if (request_state.oauth) { - if (!result.access_token) { - return error("No access token"); - } - - if (!result.token_type || result.token_type.toLowerCase() !== "bearer") { - return error("Invalid token type"); - } - - if (!result.expires_in) { - return error("No token expiration"); - } - } - - var promise = resolve(); - if (request_state.oidc && request_state.oauth) { - promise = client.validateIdTokenAndAccessTokenAsync(result.id_token, request_state.nonce, result.access_token); - } - else if (request_state.oidc) { - promise = client.validateIdTokenAsync(result.id_token, request_state.nonce); - } - - return promise.then(function (profile) { - if (profile && settings.filter_protocol_claims) { - var remove = ["nonce", "at_hash", "iat", "nbf", "exp", "aud", "iss"]; - remove.forEach(function (key) { - delete profile[key]; - }); - } - - return { - profile: profile, - id_token: result.id_token, - access_token: result.access_token, - expires_in: result.expires_in, - scope: result.scope, - session_state : result.session_state - }; - }); -} - - // exports - OidcClient._promiseFactory = _promiseFactory; - OidcClient._httpRequest = _httpRequest; - window.OidcClient = OidcClient; -})(); \ No newline at end of file diff --git a/dist/oidc-client.min.js b/dist/oidc-client.min.js deleted file mode 100644 index 3dcafd86..00000000 --- a/dist/oidc-client.min.js +++ /dev/null @@ -1,3 +0,0 @@ -!function(){function hex2b64(t){var e,r,i="";for(e=0;e+3<=t.length;e+=3)r=parseInt(t.substring(e,e+3),16),i+=b64map.charAt(r>>6)+b64map.charAt(63&r);if(e+1==t.length?(r=parseInt(t.substring(e,e+1),16),i+=b64map.charAt(r<<2)):e+2==t.length&&(r=parseInt(t.substring(e,e+2),16),i+=b64map.charAt(r>>2)+b64map.charAt((3&r)<<4)),b64pad)for(;(3&i.length)>0;)i+=b64pad;return i}function b64tohex(t){var e,r,i,n="",s=0;for(e=0;ei||(0==s?(n+=int2char(i>>2),r=3&i,s=1):1==s?(n+=int2char(r<<2|i>>4),r=15&i,s=2):2==s?(n+=int2char(r),n+=int2char(i>>2),r=3&i,s=3):(n+=int2char(r<<2|i>>4),n+=int2char(15&i),s=0));return 1==s&&(n+=int2char(r<<2)),n}function b64toBA(t){var e,r=b64tohex(t),i=new Array;for(e=0;2*e=0;){var o=e*this[t++]+r[i]+n;n=Math.floor(o/67108864),r[i++]=67108863&o}return n}function am2(t,e,r,i,n,s){for(var o=32767&e,a=e>>15;--s>=0;){var h=32767&this[t],u=this[t++]>>15,g=a*h+u*o;h=o*h+((32767&g)<<15)+r[i]+(1073741823&n),n=(h>>>30)+(g>>>15)+a*u+(n>>>30),r[i++]=1073741823&h}return n}function am3(t,e,r,i,n,s){for(var o=16383&e,a=e>>14;--s>=0;){var h=16383&this[t],u=this[t++]>>14,g=a*h+u*o;h=o*h+((16383&g)<<14)+r[i]+n,n=(h>>28)+(g>>14)+a*u,r[i++]=268435455&h}return n}function int2char(t){return BI_RM.charAt(t)}function intAt(t,e){var r=BI_RC[t.charCodeAt(e)];return null==r?-1:r}function bnpCopyTo(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s}function bnpFromInt(t){this.t=1,this.s=0>t?-1:0,t>0?this[0]=t:-1>t?this[0]=t+this.DV:this.t=0}function nbv(t){var e=nbi();return e.fromInt(t),e}function bnpFromString(t,e){var r;if(16==e)r=4;else if(8==e)r=3;else if(256==e)r=8;else if(2==e)r=1;else if(32==e)r=5;else{if(4!=e)return void this.fromRadix(t,e);r=2}this.t=0,this.s=0;for(var i=t.length,n=!1,s=0;--i>=0;){var o=8==r?255&t[i]:intAt(t,i);0>o?"-"==t.charAt(i)&&(n=!0):(n=!1,0==s?this[this.t++]=o:s+r>this.DB?(this[this.t-1]|=(o&(1<>this.DB-s):this[this.t-1]|=o<=this.DB&&(s-=this.DB))}8==r&&0!=(128&t[0])&&(this.s=-1,s>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==t;)--this.t}function bnToString(t){if(this.s<0)return"-"+this.negate().toString(t);var e;if(16==t)e=4;else if(8==t)e=3;else if(2==t)e=1;else if(32==t)e=5;else{if(4!=t)return this.toRadix(t);e=2}var r,i=(1<0)for(a>a)>0&&(n=!0,s=int2char(r));o>=0;)e>a?(r=(this[o]&(1<>(a+=this.DB-e)):(r=this[o]>>(a-=e)&i,0>=a&&(a+=this.DB,--o)),r>0&&(n=!0),n&&(s+=int2char(r));return n?s:"0"}function bnNegate(){var t=nbi();return BigInteger.ZERO.subTo(this,t),t}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(t){var e=this.s-t.s;if(0!=e)return e;var r=this.t;if(e=r-t.t,0!=e)return this.s<0?-e:e;for(;--r>=0;)if(0!=(e=this[r]-t[r]))return e;return 0}function nbits(t){var e,r=1;return 0!=(e=t>>>16)&&(t=e,r+=16),0!=(e=t>>8)&&(t=e,r+=8),0!=(e=t>>4)&&(t=e,r+=4),0!=(e=t>>2)&&(t=e,r+=2),0!=(e=t>>1)&&(t=e,r+=1),r}function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(t,e){var r;for(r=this.t-1;r>=0;--r)e[r+t]=this[r];for(r=t-1;r>=0;--r)e[r]=0;e.t=this.t+t,e.s=this.s}function bnpDRShiftTo(t,e){for(var r=t;r=0;--r)e[r+o+1]=this[r]>>n|a,a=(this[r]&s)<=0;--r)e[r]=0;e[o]=a,e.t=this.t+o+1,e.s=this.s,e.clamp()}function bnpRShiftTo(t,e){e.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t)return void(e.t=0);var i=t%this.DB,n=this.DB-i,s=(1<>i;for(var o=r+1;o>i;i>0&&(e[this.t-r-1]|=(this.s&s)<r;)i+=this[r]-t[r],e[r++]=i&this.DM,i>>=this.DB;if(t.t>=this.DB;i+=this.s}else{for(i+=this.s;r>=this.DB;i-=t.s}e.s=0>i?-1:0,-1>i?e[r++]=this.DV+i:i>0&&(e[r++]=i),e.t=r,e.clamp()}function bnpMultiplyTo(t,e){var r=this.abs(),i=t.abs(),n=r.t;for(e.t=n+i.t;--n>=0;)e[n]=0;for(n=0;n=0;)t[r]=0;for(r=0;r=e.DV&&(t[r+e.t]-=e.DV,t[r+e.t+1]=1)}t.t>0&&(t[t.t-1]+=e.am(r,e[r],t,2*r,0,1)),t.s=0,t.clamp()}function bnpDivRemTo(t,e,r){var i=t.abs();if(!(i.t<=0)){var n=this.abs();if(n.t0?(i.lShiftTo(h,s),n.lShiftTo(h,r)):(i.copyTo(s),n.copyTo(r));var u=s.t,g=s[u-1];if(0!=g){var c=g*(1<1?s[u-2]>>this.F2:0),p=this.FV/c,f=(1<=0&&(r[r.t++]=1,r.subTo(v,r)),BigInteger.ONE.dlShiftTo(u,v),v.subTo(s,s);s.t=0;){var S=r[--d]==g?this.DM:Math.floor(r[d]*p+(r[d-1]+l)*f);if((r[d]+=s.am(0,S,r,y,0,u))0&&r.rShiftTo(h,r),0>o&&BigInteger.ZERO.subTo(r,r)}}}function bnMod(t){var e=nbi();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(BigInteger.ZERO)>0&&t.subTo(e,e),e}function Classic(t){this.m=t}function cConvert(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function cRevert(t){return t}function cReduce(t){t.divRemTo(this.m,null,t)}function cMulTo(t,e,r){t.multiplyTo(e,r),this.reduce(r)}function cSqrTo(t,e){t.squareTo(e),this.reduce(e)}function bnpInvDigit(){if(this.t<1)return 0;var t=this[0];if(0==(1&t))return 0;var e=3&t;return e=e*(2-(15&t)*e)&15,e=e*(2-(255&t)*e)&255,e=e*(2-((65535&t)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function Montgomery(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(e,e),e}function montRevert(t){var e=nbi();return t.copyTo(e),this.reduce(e),e}function montReduce(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e>15)*this.mpl&this.um)<<15)&t.DM;for(r=e+this.m.t,t[r]+=this.m.am(0,i,t,e,0,this.m.t);t[r]>=t.DV;)t[r]-=t.DV,t[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function montSqrTo(t,e){t.squareTo(e),this.reduce(e)}function montMulTo(t,e,r){t.multiplyTo(e,r),this.reduce(r)}function bnpIsEven(){return 0==(this.t>0?1&this[0]:this.s)}function bnpExp(t,e){if(t>4294967295||1>t)return BigInteger.ONE;var r=nbi(),i=nbi(),n=e.convert(this),s=nbits(t)-1;for(n.copyTo(r);--s>=0;)if(e.sqrTo(r,i),(t&1<0)e.mulTo(i,n,r);else{var o=r;r=i,i=o}return e.revert(r)}function bnModPowInt(t,e){var r;return r=256>t||e.isEven()?new Classic(e):new Montgomery(e),this.exp(t,r)}function bnClone(){var t=nbi();return this.copyTo(t),t}function bnIntValue(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return 0==this.t?this.s:this[0]<<16>>16}function bnpChunkSize(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function bnSigNum(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function bnpToRadix(t){if(null==t&&(t=10),0==this.signum()||2>t||t>36)return"0";var e=this.chunkSize(t),r=Math.pow(t,e),i=nbv(r),n=nbi(),s=nbi(),o="";for(this.divRemTo(i,n,s);n.signum()>0;)o=(r+s.intValue()).toString(t).substr(1)+o,n.divRemTo(i,n,s);return s.intValue().toString(t)+o}function bnpFromRadix(t,e){this.fromInt(0),null==e&&(e=10);for(var r=this.chunkSize(e),i=Math.pow(e,r),n=!1,s=0,o=0,a=0;ah?"-"==t.charAt(a)&&0==this.signum()&&(n=!0):(o=e*o+h,++s>=r&&(this.dMultiply(i),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(o,0)),n&&BigInteger.ZERO.subTo(this,this)}function bnpFromNumber(t,e,r){if("number"==typeof e)if(2>t)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(t-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(BigInteger.ONE.shiftLeft(t-1),this);else{var i=new Array,n=7&t;i.length=(t>>3)+1,e.nextBytes(i),n>0?i[0]&=(1<0)for(i>i)!=(this.s&this.DM)>>i&&(e[n++]=r|this.s<=0;)8>i?(r=(this[t]&(1<>(i+=this.DB-8)):(r=this[t]>>(i-=8)&255,0>=i&&(i+=this.DB,--t)),0!=(128&r)&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(e[n++]=r);return e}function bnEquals(t){return 0==this.compareTo(t)}function bnMin(t){return this.compareTo(t)<0?this:t}function bnMax(t){return this.compareTo(t)>0?this:t}function bnpBitwiseTo(t,e,r){var i,n,s=Math.min(t.t,this.t);for(i=0;s>i;++i)r[i]=e(this[i],t[i]);if(t.tt?this.rShiftTo(-t,e):this.lShiftTo(t,e),e}function bnShiftRight(t){var e=nbi();return 0>t?this.lShiftTo(-t,e):this.rShiftTo(t,e),e}function lbit(t){if(0==t)return-1;var e=0;return 0==(65535&t)&&(t>>=16,e+=16),0==(255&t)&&(t>>=8,e+=8),0==(15&t)&&(t>>=4,e+=4),0==(3&t)&&(t>>=2,e+=2),0==(1&t)&&++e,e}function bnGetLowestSetBit(){for(var t=0;t=this.t?0!=this.s:0!=(this[e]&1<r;)i+=this[r]+t[r],e[r++]=i&this.DM,i>>=this.DB;if(t.t>=this.DB;i+=this.s}else{for(i+=this.s;r>=this.DB;i+=t.s}e.s=0>i?-1:0,i>0?e[r++]=i:-1>i&&(e[r++]=this.DV+i),e.t=r,e.clamp()}function bnAdd(t){var e=nbi();return this.addTo(t,e),e}function bnSubtract(t){var e=nbi();return this.subTo(t,e),e}function bnMultiply(t){var e=nbi();return this.multiplyTo(t,e),e}function bnSquare(){var t=nbi();return this.squareTo(t),t}function bnDivide(t){var e=nbi();return this.divRemTo(t,e,null),e}function bnRemainder(t){var e=nbi();return this.divRemTo(t,null,e),e}function bnDivideAndRemainder(t){var e=nbi(),r=nbi();return this.divRemTo(t,e,r),new Array(e,r)}function bnpDMultiply(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function bnpDAddOffset(t,e){if(0!=t){for(;this.t<=e;)this[this.t++]=0;for(this[e]+=t;this[e]>=this.DV;)this[e]-=this.DV,++e>=this.t&&(this[this.t++]=0),++this[e]}}function NullExp(){}function nNop(t){return t}function nMulTo(t,e,r){t.multiplyTo(e,r)}function nSqrTo(t,e){t.squareTo(e)}function bnPow(t){return this.exp(t,new NullExp)}function bnpMultiplyLowerTo(t,e,r){var i=Math.min(this.t+t.t,e);for(r.s=0,r.t=i;i>0;)r[--i]=0;var n;for(n=r.t-this.t;n>i;++i)r[i+this.t]=this.am(0,t[i],r,i,0,this.t);for(n=Math.min(t.t,e);n>i;++i)this.am(0,t[i],r,i,0,e-i);r.clamp()}function bnpMultiplyUpperTo(t,e,r){--e;var i=r.t=this.t+t.t-e;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(e-this.t,0);i2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=nbi();return t.copyTo(e),this.reduce(e),e}function barrettRevert(t){return t}function barrettReduce(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function barrettSqrTo(t,e){t.squareTo(e),this.reduce(e)}function barrettMulTo(t,e,r){t.multiplyTo(e,r),this.reduce(r)}function bnModPow(t,e){var r,i,n=t.bitLength(),s=nbv(1);if(0>=n)return s;r=18>n?1:48>n?3:144>n?4:768>n?5:6,i=8>n?new Classic(e):e.isEven()?new Barrett(e):new Montgomery(e);var o=new Array,a=3,h=r-1,u=(1<1){var g=nbi();for(i.sqrTo(o[1],g);u>=a;)o[a]=nbi(),i.mulTo(g,o[a-2],o[a]),a+=2}var c,p,f=t.t-1,l=!0,d=nbi();for(n=nbits(t[f])-1;f>=0;){for(n>=h?c=t[f]>>n-h&u:(c=(t[f]&(1<0&&(c|=t[f-1]>>this.DB+n-h)),a=r;0==(1&c);)c>>=1,--a;if((n-=a)<0&&(n+=this.DB,--f),l)o[c].copyTo(s),l=!1;else{for(;a>1;)i.sqrTo(s,d),i.sqrTo(d,s),a-=2;a>0?i.sqrTo(s,d):(p=s,s=d,d=p),i.mulTo(d,o[c],s)}for(;f>=0&&0==(t[f]&1<s)return e;for(s>n&&(s=n),s>0&&(e.rShiftTo(s,e),r.rShiftTo(s,r));e.signum()>0;)(n=e.getLowestSetBit())>0&&e.rShiftTo(n,e),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),e.compareTo(r)>=0?(e.subTo(r,e),e.rShiftTo(1,e)):(r.subTo(e,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r}function bnpModInt(t){if(0>=t)return 0;var e=this.DV%t,r=this.s<0?t-1:0;if(this.t>0)if(0==e)r=this[0]%t;else for(var i=this.t-1;i>=0;--i)r=(e*r+this[i])%t;return r}function bnModInverse(t){var e=t.isEven();if(this.isEven()&&e||0==t.signum())return BigInteger.ZERO;for(var r=t.clone(),i=this.clone(),n=nbv(1),s=nbv(0),o=nbv(0),a=nbv(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),e?(n.isEven()&&s.isEven()||(n.addTo(this,n),s.subTo(t,s)),n.rShiftTo(1,n)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;i.isEven();)i.rShiftTo(1,i),e?(o.isEven()&&a.isEven()||(o.addTo(this,o),a.subTo(t,a)),o.rShiftTo(1,o)):a.isEven()||a.subTo(t,a),a.rShiftTo(1,a);r.compareTo(i)>=0?(r.subTo(i,r),e&&n.subTo(o,n),s.subTo(a,s)):(i.subTo(r,i),e&&o.subTo(n,o),a.subTo(s,a))}return 0!=i.compareTo(BigInteger.ONE)?BigInteger.ZERO:a.compareTo(t)>=0?a.subtract(t):a.signum()<0?(a.addTo(t,a),a.signum()<0?a.add(t):a):a}function bnIsProbablePrime(t){var e,r=this.abs();if(1==r.t&&r[0]<=lowprimes[lowprimes.length-1]){for(e=0;ei;)i*=lowprimes[n++];for(i=r.modInt(i);n>e;)if(i%lowprimes[e++]==0)return!1}return r.millerRabin(t)}function bnpMillerRabin(t){var e=this.subtract(BigInteger.ONE),r=e.getLowestSetBit();if(0>=r)return!1;var i=e.shiftRight(r);t=t+1>>1,t>lowprimes.length&&(t=lowprimes.length);for(var n=nbi(),s=0;t>s;++s){n.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var o=n.modPow(i,this);if(0!=o.compareTo(BigInteger.ONE)&&0!=o.compareTo(e)){for(var a=1;a++t?"0"+t.toString(16):t.toString(16)}function pkcs1pad2(t,e){if(e=0&&e>0;){var n=t.charCodeAt(i--);128>n?r[--e]=n:n>127&&2048>n?(r[--e]=63&n|128,r[--e]=n>>6|192):(r[--e]=63&n|128,r[--e]=n>>6&63|128,r[--e]=n>>12|224)}r[--e]=0;for(var s=new SecureRandom,o=new Array;e>2;){for(o[0]=0;0==o[0];)s.nextBytes(o);r[--e]=o[0]}return r[--e]=2,r[--e]=0,new BigInteger(r)}function oaep_mgf1_arr(t,e,r){for(var i="",n=0;i.length>24,(16711680&n)>>16,(65280&n)>>8,255&n]))),n+=1;return i}function oaep_pad(t,e,r){if(t.length+2*SHA1_SIZE+2>e)throw"Message too long for RSA";var i,n="";for(i=0;i0&&e.length>0?(this.n=parseBigInt(t,16),this.e=parseInt(e,16)):alert("Invalid RSA public key")}function RSADoPublic(t){return t.modPowInt(this.e,this.n)}function RSAEncrypt(t){var e=pkcs1pad2(t,this.n.bitLength()+7>>3);if(null==e)return null;var r=this.doPublic(e);if(null==r)return null;var i=r.toString(16);return 0==(1&i.length)?i:"0"+i}function RSAEncryptOAEP(t,e){var r=oaep_pad(t,this.n.bitLength()+7>>3,e);if(null==r)return null;var i=this.doPublic(r);if(null==i)return null;var n=i.toString(16);return 0==(1&n.length)?n:"0"+n}function pkcs1unpad2(t,e){for(var r=t.toByteArray(),i=0;i=r.length)return null;for(var n="";++is?n+=String.fromCharCode(s):s>191&&224>s?(n+=String.fromCharCode((31&s)<<6|63&r[i+1]),++i):(n+=String.fromCharCode((15&s)<<12|(63&r[i+1])<<6|63&r[i+2]),i+=2)}return n}function oaep_mgf1_str(t,e,r){for(var i="",n=0;i.length>24,(16711680&n)>>16,(65280&n)>>8,255&n])),n+=1;return i}function oaep_unpad(t,e,r){t=t.toByteArray();var i;for(i=0;i0&&e.length>0?(this.n=parseBigInt(t,16),this.e=parseInt(e,16),this.d=parseBigInt(r,16)):alert("Invalid RSA private key")}function RSASetPrivateEx(t,e,r,i,n,s,o,a){if(this.isPrivate=!0,null==t)throw"RSASetPrivateEx N == null";if(null==e)throw"RSASetPrivateEx E == null";if(0==t.length)throw"RSASetPrivateEx N.length == 0";if(0==e.length)throw"RSASetPrivateEx E.length == 0";null!=t&&null!=e&&t.length>0&&e.length>0?(this.n=parseBigInt(t,16),this.e=parseInt(e,16),this.d=parseBigInt(r,16),this.p=parseBigInt(i,16),this.q=parseBigInt(n,16),this.dmp1=parseBigInt(s,16),this.dmq1=parseBigInt(o,16),this.coeff=parseBigInt(a,16)):alert("Invalid RSA private key in RSASetPrivateEx")}function RSAGenerate(t,e){var r=new SecureRandom,i=t>>1;this.e=parseInt(e,16);for(var n=new BigInteger(e,16);;){for(;this.p=new BigInteger(t-i,1,r),0!=this.p.subtract(BigInteger.ONE).gcd(n).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(i,1,r),0!=this.q.subtract(BigInteger.ONE).gcd(n).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var s=this.p;this.p=this.q,this.q=s}var o=this.p.subtract(BigInteger.ONE),a=this.q.subtract(BigInteger.ONE),h=o.multiply(a);if(0==h.gcd(n).compareTo(BigInteger.ONE)){this.n=this.p.multiply(this.q),this.d=n.modInverse(h),this.dmp1=this.d.mod(o),this.dmq1=this.d.mod(a),this.coeff=this.q.modInverse(this.p);break}}this.isPrivate=!0}function RSADoPrivate(t){if(null==this.p||null==this.q)return t.modPow(this.d,this.n);for(var e=t.mod(this.p).modPow(this.dmp1,this.p),r=t.mod(this.q).modPow(this.dmq1,this.q);e.compareTo(r)<0;)e=e.add(this.p);return e.subtract(r).multiply(this.coeff).mod(this.p).multiply(this.q).add(r)}function RSADecrypt(t){var e=parseBigInt(t,16),r=this.doPrivate(e);return null==r?null:pkcs1unpad2(r,this.n.bitLength()+7>>3)}function RSADecryptOAEP(t,e){var r=parseBigInt(t,16),i=this.doPrivate(r);return null==i?null:oaep_unpad(i,this.n.bitLength()+7>>3,e)}function _rsapem_pemToBase64(t){var e=t;return e=e.replace("-----BEGIN RSA PRIVATE KEY-----",""),e=e.replace("-----END RSA PRIVATE KEY-----",""),e=e.replace(/[ \n]+/g,"")}function _rsapem_getPosArrayOfChildrenFromHex(t){var e=new Array,r=ASN1HEX.getStartPosOfV_AtObj(t,0),i=ASN1HEX.getPosOfNextSibling_AtObj(t,r),n=ASN1HEX.getPosOfNextSibling_AtObj(t,i),s=ASN1HEX.getPosOfNextSibling_AtObj(t,n),o=ASN1HEX.getPosOfNextSibling_AtObj(t,s),a=ASN1HEX.getPosOfNextSibling_AtObj(t,o),h=ASN1HEX.getPosOfNextSibling_AtObj(t,a),u=ASN1HEX.getPosOfNextSibling_AtObj(t,h),g=ASN1HEX.getPosOfNextSibling_AtObj(t,u);return e.push(r,i,n,s,o,a,h,u,g),e}function _rsapem_getHexValueArrayOfChildrenFromHex(t){var e=_rsapem_getPosArrayOfChildrenFromHex(t),r=ASN1HEX.getHexOfV_AtObj(t,e[0]),i=ASN1HEX.getHexOfV_AtObj(t,e[1]),n=ASN1HEX.getHexOfV_AtObj(t,e[2]),s=ASN1HEX.getHexOfV_AtObj(t,e[3]),o=ASN1HEX.getHexOfV_AtObj(t,e[4]),a=ASN1HEX.getHexOfV_AtObj(t,e[5]),h=ASN1HEX.getHexOfV_AtObj(t,e[6]),u=ASN1HEX.getHexOfV_AtObj(t,e[7]),g=ASN1HEX.getHexOfV_AtObj(t,e[8]),c=new Array;return c.push(r,i,n,s,o,a,h,u,g),c}function _rsapem_readPrivateKeyFromASN1HexString(t){var e=_rsapem_getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])}function _rsapem_readPrivateKeyFromPEMString(t){var e=_rsapem_pemToBase64(t),r=b64tohex(e),i=_rsapem_getHexValueArrayOfChildrenFromHex(r);this.setPrivateEx(i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8])}function _rsasign_getHexPaddedDigestInfoForString(t,e,r){var i=function(t){return KJUR.crypto.Util.hashString(t,r)},n=i(t);return KJUR.crypto.Util.getPaddedDigestInfoHex(n,r,e)}function _zeroPaddingOfSignature(t,e){for(var r="",i=e/4-t.length,n=0;i>n;n++)r+="0";return r+t}function _rsasign_signString(t,e){var r=function(t){return KJUR.crypto.Util.hashString(t,e)},i=r(t);return this.signWithMessageHash(i,e)}function _rsasign_signWithMessageHash(t,e){var r=KJUR.crypto.Util.getPaddedDigestInfoHex(t,e,this.n.bitLength()),i=parseBigInt(r,16),n=this.doPrivate(i),s=n.toString(16);return _zeroPaddingOfSignature(s,this.n.bitLength())}function _rsasign_signStringWithSHA1(t){return _rsasign_signString.call(this,t,"sha1")}function _rsasign_signStringWithSHA256(t){return _rsasign_signString.call(this,t,"sha256")}function pss_mgf1_str(t,e,r){for(var i="",n=0;i.length>24,(16711680&n)>>16,(65280&n)>>8,255&n])))),n+=1;return i}function _rsasign_signStringPSS(t,e,r){var i=function(t){return KJUR.crypto.Util.hashHex(t,e)},n=i(rstrtohex(t));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,e,r)}function _rsasign_signWithMessageHashPSS(t,e,r){var i,n=hextorstr(t),s=n.length,o=this.n.bitLength()-1,a=Math.ceil(o/8),h=function(t){return KJUR.crypto.Util.hashHex(t,e)};if(-1===r||void 0===r)r=s;else if(-2===r)r=a-s-2;else if(-2>r)throw"invalid salt length";if(s+r+2>a)throw"data too long";var u="";r>0&&(u=new Array(r),(new SecureRandom).nextBytes(u),u=String.fromCharCode.apply(String,u));var g=hextorstr(h(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+n+u))),c=[];for(i=0;a-r-s-2>i;i+=1)c[i]=0;var p=String.fromCharCode.apply(String,c)+""+u,f=pss_mgf1_str(g,p.length,h),l=[];for(i=0;i>8*a-o&255;for(l[0]&=~d,i=0;s>i;i++)l.push(g.charCodeAt(i));return l.push(188),_zeroPaddingOfSignature(this.doPrivate(new BigInteger(l)).toString(16),this.n.bitLength())}function _rsasign_getDecryptSignatureBI(t,e,r){var i=new RSAKey;i.setPublic(e,r);var n=i.doPublic(t);return n}function _rsasign_getHexDigestInfoFromSig(t,e,r){var i=_rsasign_getDecryptSignatureBI(t,e,r),n=i.toString(16).replace(/^1f+00/,"");return n}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(t){for(var e in KJUR.crypto.Util.DIGESTINFOHEAD){var r=KJUR.crypto.Util.DIGESTINFOHEAD[e],i=r.length;if(t.substring(0,i)==r){var n=[e,t.substring(i)];return n}}return[]}function _rsasign_verifySignatureWithArgs(t,e,r,i){var n=_rsasign_getHexDigestInfoFromSig(e,r,i),s=_rsasign_getAlgNameAndHashFromHexDisgestInfo(n);if(0==s.length)return!1;var o=s[0],a=s[1],h=function(t){return KJUR.crypto.Util.hashString(t,o)},u=h(t);return a==u}function _rsasign_verifyHexSignatureForMessage(t,e){var r=parseBigInt(t,16),i=_rsasign_verifySignatureWithArgs(e,r,this.n.toString(16),this.e.toString(16));return i}function _rsasign_verifyString(t,e){e=e.replace(_RE_HEXDECONLY,""),e=e.replace(/[ \n]+/g,"");var r=parseBigInt(e,16);if(r.bitLength()>this.n.bitLength())return 0;var i=this.doPublic(r),n=i.toString(16).replace(/^1f+00/,""),s=_rsasign_getAlgNameAndHashFromHexDisgestInfo(n);if(0==s.length)return!1;var o=s[0],a=s[1],h=function(t){return KJUR.crypto.Util.hashString(t,o)},u=h(t);return a==u}function _rsasign_verifyWithMessageHash(t,e){e=e.replace(_RE_HEXDECONLY,""),e=e.replace(/[ \n]+/g,"");var r=parseBigInt(e,16);if(r.bitLength()>this.n.bitLength())return 0;var i=this.doPublic(r),n=i.toString(16).replace(/^1f+00/,""),s=_rsasign_getAlgNameAndHashFromHexDisgestInfo(n);if(0==s.length)return!1;var o=(s[0],s[1]);return o==t}function _rsasign_verifyStringPSS(t,e,r,i){var n=function(t){return KJUR.crypto.Util.hashHex(t,r)},s=n(rstrtohex(t));return void 0===i&&(i=-1),this.verifyWithMessageHashPSS(s,e,r,i)}function _rsasign_verifyWithMessageHashPSS(t,e,r,i){var n=new BigInteger(e,16);if(n.bitLength()>this.n.bitLength())return!1;var s,o=function(t){return KJUR.crypto.Util.hashHex(t,r)},a=hextorstr(t),h=a.length,u=this.n.bitLength()-1,g=Math.ceil(u/8);if(-1===i||void 0===i)i=h;else if(-2===i)i=g-h-2;else if(-2>i)throw"invalid salt length";if(h+i+2>g)throw"data too long";var c=this.doPublic(n).toByteArray();for(s=0;s>8*g-u&255;if(0!==(p.charCodeAt(0)&l))throw"bits beyond keysize not zero";var d=pss_mgf1_str(f,p.length,o),y=[];for(s=0;ss;s+=1)if(0!==y[s])throw"leftmost octets not zero";if(1!==y[v])throw"0x01 marker not found";return f===hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+a+String.fromCharCode.apply(String,y.slice(-i)))))}function X509(){this.subjectPublicKeyRSA=null,this.subjectPublicKeyRSA_hN=null,this.subjectPublicKeyRSA_hE=null,this.hex=null,this.getSerialNumberHex=function(){return ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,1])},this.getIssuerHex=function(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3])},this.getIssuerString=function(){return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,3]))},this.getSubjectHex=function(){return ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5])},this.getSubjectString=function(){return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex,0,[0,5]))},this.getNotBefore=function(){var t=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,0]);return t=t.replace(/(..)/g,"%$1"),t=decodeURIComponent(t)},this.getNotAfter=function(){var t=ASN1HEX.getDecendantHexVByNthList(this.hex,0,[0,4,1]);return t=t.replace(/(..)/g,"%$1"),t=decodeURIComponent(t)},this.readCertPEM=function(t){var e=X509.pemToHex(t),r=X509.getPublicKeyHexArrayFromCertHex(e),i=new RSAKey;i.setPublic(r[0],r[1]),this.subjectPublicKeyRSA=i,this.subjectPublicKeyRSA_hN=r[0],this.subjectPublicKeyRSA_hE=r[1],this.hex=e},this.readCertPEMWithoutRSAInit=function(t){var e=X509.pemToHex(t),r=X509.getPublicKeyHexArrayFromCertHex(e);this.subjectPublicKeyRSA.setPublic(r[0],r[1]),this.subjectPublicKeyRSA_hN=r[0],this.subjectPublicKeyRSA_hE=r[1],this.hex=e}}function Base64x(){}function stoBA(t){for(var e=new Array,r=0;r=0&&(t=t.substr(e+1));for(var r,i={},n=/([^&=]+)=([^&]*)/g,s=0;r=n.exec(t);)if(i[decodeURIComponent(r[1])]=decodeURIComponent(r[2]),s++>50)return{error:"Response exceeded expected number of parameters"};for(var o in i)return i}function getJson(t,e){log("getJson",t);var r={};return e&&(r.headers={Authorization:"Bearer "+e}),_httpRequest.getJSON(t,r)}function OidcClient(t){this._settings=t||{},this._settings.request_state_key||(this._settings.request_state_key="OidcClient.request_state"),this._settings.request_state_store||(this._settings.request_state_store=window.localStorage),"undefined"==typeof this._settings.load_user_profile&&(this._settings.load_user_profile=!0),"undefined"==typeof this._settings.filter_protocol_claims&&(this._settings.filter_protocol_claims=!0),this._settings.authority&&this._settings.authority.indexOf(".well-known/openid-configuration")<0&&("/"!==this._settings.authority[this._settings.authority.length-1]&&(this._settings.authority+="/"),this._settings.authority+=".well-known/openid-configuration"),this._settings.response_type||(this._settings.response_type="id_token token"),Object.defineProperty(this,"isOidc",{get:function(){if(this._settings.response_type){var t=this._settings.response_type.split(/\s+/g).filter(function(t){return"id_token"===t});return!!t[0]}return!1}}),Object.defineProperty(this,"isOAuth",{get:function(){if(this._settings.response_type){var t=this._settings.response_type.split(/\s+/g).filter(function(t){return"token"===t});return!!t[0]}return!1}})}var _promiseFactory,_httpRequest,CryptoJS=CryptoJS||function(t,e){var r={},i=r.lib={},n=i.Base=function(){function t(){}return{extend:function(e){t.prototype=this;var r=new t;return e&&r.mixIn(e),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),s=i.WordArray=n.extend({init:function(t,r){t=this.words=t||[],this.sigBytes=r!=e?r:4*t.length},toString:function(t){return(t||a).stringify(this)},concat:function(t){var e=this.words,r=t.words,i=this.sigBytes,n=t.sigBytes;if(this.clamp(),i%4)for(var s=0;n>s;s++){var o=r[s>>>2]>>>24-s%4*8&255;e[i+s>>>2]|=o<<24-(i+s)%4*8}else if(r.length>65535)for(var s=0;n>s;s+=4)e[i+s>>>2]=r[s>>>2];else e.push.apply(e,r);return this.sigBytes+=n,this},clamp:function(){var e=this.words,r=this.sigBytes;e[r>>>2]&=4294967295<<32-r%4*8,e.length=t.ceil(r/4)},clone:function(){var t=n.clone.call(this);return t.words=this.words.slice(0),t},random:function(e){for(var r=[],i=0;e>i;i+=4)r.push(4294967296*t.random()|0);return new s.init(r,e)}}),o=r.enc={},a=o.Hex={stringify:function(t){for(var e=t.words,r=t.sigBytes,i=[],n=0;r>n;n++){var s=e[n>>>2]>>>24-n%4*8&255;i.push((s>>>4).toString(16)),i.push((15&s).toString(16))}return i.join("")},parse:function(t){for(var e=t.length,r=[],i=0;e>i;i+=2)r[i>>>3]|=parseInt(t.substr(i,2),16)<<24-i%8*4;return new s.init(r,e/2)}},h=o.Latin1={stringify:function(t){for(var e=t.words,r=t.sigBytes,i=[],n=0;r>n;n++){var s=e[n>>>2]>>>24-n%4*8&255;i.push(String.fromCharCode(s))}return i.join("")},parse:function(t){for(var e=t.length,r=[],i=0;e>i;i++)r[i>>>2]|=(255&t.charCodeAt(i))<<24-i%4*8;return new s.init(r,e)}},u=o.Utf8={stringify:function(t){try{return decodeURIComponent(escape(h.stringify(t)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(t){return h.parse(unescape(encodeURIComponent(t)))}},g=i.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=u.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var r=this._data,i=r.words,n=r.sigBytes,o=this.blockSize,a=4*o,h=n/a;h=e?t.ceil(h):t.max((0|h)-this._minBufferSize,0);var u=h*o,g=t.min(4*u,n);if(u){for(var c=0;u>c;c+=o)this._doProcessBlock(i,c);var p=i.splice(0,u);r.sigBytes-=g}return new s.init(p,g)},clone:function(){var t=n.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0}),c=(i.Hasher=g.extend({cfg:n.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){t&&this._append(t);var e=this._doFinalize();return e},blockSize:16,_createHelper:function(t){return function(e,r){return new t.init(r).finalize(e)}},_createHmacHelper:function(t){return function(e,r){return new c.HMAC.init(t,r).finalize(e)}}}),r.algo={});return r}(Math);!function(){var t=CryptoJS,e=t.lib,r=e.WordArray,i=e.Hasher,n=t.algo,s=[],o=n.SHA1=i.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(t,e){for(var r=this._hash.words,i=r[0],n=r[1],o=r[2],a=r[3],h=r[4],u=0;80>u;u++){if(16>u)s[u]=0|t[e+u];else{var g=s[u-3]^s[u-8]^s[u-14]^s[u-16];s[u]=g<<1|g>>>31}var c=(i<<5|i>>>27)+h+s[u];c+=20>u?(n&o|~n&a)+1518500249:40>u?(n^o^a)+1859775393:60>u?(n&o|n&a|o&a)-1894007588:(n^o^a)-899497514,h=a,a=o,o=n<<30|n>>>2,n=i,i=c}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+h|0},_doFinalize:function(){var t=this._data,e=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;return e[i>>>5]|=128<<24-i%32,e[(i+64>>>9<<4)+14]=Math.floor(r/4294967296),e[(i+64>>>9<<4)+15]=r,t.sigBytes=4*e.length,this._process(),this._hash},clone:function(){var t=i.clone.call(this);return t._hash=this._hash.clone(),t}});t.SHA1=i._createHelper(o),t.HmacSHA1=i._createHmacHelper(o)}(),function(t){var e=CryptoJS,r=e.lib,i=r.WordArray,n=r.Hasher,s=e.algo,o=[],a=[];!function(){function e(e){for(var r=t.sqrt(e),i=2;r>=i;i++)if(!(e%i))return!1;return!0}function r(t){return 4294967296*(t-(0|t))|0}for(var i=2,n=0;64>n;)e(i)&&(8>n&&(o[n]=r(t.pow(i,.5))),a[n]=r(t.pow(i,1/3)),n++),i++}();var h=[],u=s.SHA256=n.extend({_doReset:function(){this._hash=new i.init(o.slice(0))},_doProcessBlock:function(t,e){for(var r=this._hash.words,i=r[0],n=r[1],s=r[2],o=r[3],u=r[4],g=r[5],c=r[6],p=r[7],f=0;64>f;f++){if(16>f)h[f]=0|t[e+f];else{var l=h[f-15],d=(l<<25|l>>>7)^(l<<14|l>>>18)^l>>>3,y=h[f-2],v=(y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10;h[f]=d+h[f-7]+v+h[f-16]}var S=u&g^~u&c,b=i&n^i&s^n&s,m=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),A=(u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25),_=p+A+S+a[f]+h[f],w=m+b;p=c,c=g,g=u,u=o+_|0,o=s,s=n,n=i,i=_+w|0}r[0]=r[0]+i|0,r[1]=r[1]+n|0,r[2]=r[2]+s|0,r[3]=r[3]+o|0,r[4]=r[4]+u|0,r[5]=r[5]+g|0,r[6]=r[6]+c|0,r[7]=r[7]+p|0},_doFinalize:function(){var e=this._data,r=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return r[n>>>5]|=128<<24-n%32,r[(n+64>>>9<<4)+14]=t.floor(i/4294967296),r[(n+64>>>9<<4)+15]=i,e.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var t=n.clone.call(this);return t._hash=this._hash.clone(),t}});e.SHA256=n._createHelper(u),e.HmacSHA256=n._createHmacHelper(u)}(Math),function(t){{var e=CryptoJS,r=e.lib,i=r.Base,n=r.WordArray,s=e.x64={};s.Word=i.extend({init:function(t,e){this.high=t,this.low=e}}),s.WordArray=i.extend({init:function(e,r){e=this.words=e||[],this.sigBytes=r!=t?r:8*e.length},toX32:function(){for(var t=this.words,e=t.length,r=[],i=0;e>i;i++){var s=t[i];r.push(s.high),r.push(s.low)}return n.create(r,this.sigBytes)},clone:function(){for(var t=i.clone.call(this),e=t.words=this.words.slice(0),r=e.length,n=0;r>n;n++)e[n]=e[n].clone();return t}})}}(),function(){function t(){return s.create.apply(s,arguments)}var e=CryptoJS,r=e.lib,i=r.Hasher,n=e.x64,s=n.Word,o=n.WordArray,a=e.algo,h=[t(1116352408,3609767458),t(1899447441,602891725),t(3049323471,3964484399),t(3921009573,2173295548),t(961987163,4081628472),t(1508970993,3053834265),t(2453635748,2937671579),t(2870763221,3664609560),t(3624381080,2734883394),t(310598401,1164996542),t(607225278,1323610764),t(1426881987,3590304994),t(1925078388,4068182383),t(2162078206,991336113),t(2614888103,633803317),t(3248222580,3479774868),t(3835390401,2666613458),t(4022224774,944711139),t(264347078,2341262773),t(604807628,2007800933),t(770255983,1495990901),t(1249150122,1856431235),t(1555081692,3175218132),t(1996064986,2198950837),t(2554220882,3999719339),t(2821834349,766784016),t(2952996808,2566594879),t(3210313671,3203337956),t(3336571891,1034457026),t(3584528711,2466948901),t(113926993,3758326383),t(338241895,168717936),t(666307205,1188179964),t(773529912,1546045734),t(1294757372,1522805485),t(1396182291,2643833823),t(1695183700,2343527390),t(1986661051,1014477480),t(2177026350,1206759142),t(2456956037,344077627),t(2730485921,1290863460),t(2820302411,3158454273),t(3259730800,3505952657),t(3345764771,106217008),t(3516065817,3606008344),t(3600352804,1432725776),t(4094571909,1467031594),t(275423344,851169720),t(430227734,3100823752),t(506948616,1363258195),t(659060556,3750685593),t(883997877,3785050280),t(958139571,3318307427),t(1322822218,3812723403),t(1537002063,2003034995),t(1747873779,3602036899),t(1955562222,1575990012),t(2024104815,1125592928),t(2227730452,2716904306),t(2361852424,442776044),t(2428436474,593698344),t(2756734187,3733110249),t(3204031479,2999351573),t(3329325298,3815920427),t(3391569614,3928383900),t(3515267271,566280711),t(3940187606,3454069534),t(4118630271,4000239992),t(116418474,1914138554),t(174292421,2731055270),t(289380356,3203993006),t(460393269,320620315),t(685471733,587496836),t(852142971,1086792851),t(1017036298,365543100),t(1126000580,2618297676),t(1288033470,3409855158),t(1501505948,4234509866),t(1607167915,987167468),t(1816402316,1246189591)],u=[];!function(){for(var e=0;80>e;e++)u[e]=t()}();var g=a.SHA512=i.extend({_doReset:function(){this._hash=new o.init([new s.init(1779033703,4089235720),new s.init(3144134277,2227873595),new s.init(1013904242,4271175723),new s.init(2773480762,1595750129),new s.init(1359893119,2917565137),new s.init(2600822924,725511199),new s.init(528734635,4215389547),new s.init(1541459225,327033209)])},_doProcessBlock:function(t,e){for(var r=this._hash.words,i=r[0],n=r[1],s=r[2],o=r[3],a=r[4],g=r[5],c=r[6],p=r[7],f=i.high,l=i.low,d=n.high,y=n.low,v=s.high,S=s.low,b=o.high,m=o.low,A=a.high,_=a.low,w=g.high,x=g.low,R=c.high,H=c.low,B=p.high,I=p.low,E=f,P=l,T=d,O=y,N=v,C=S,D=b,j=m,M=A,J=_,K=w,U=x,k=R,L=H,W=B,F=I,X=0;80>X;X++){var V=u[X];if(16>X)var q=V.high=0|t[e+2*X],z=V.low=0|t[e+2*X+1];else{var G=u[X-15],Z=G.high,$=G.low,Y=(Z>>>1|$<<31)^(Z>>>8|$<<24)^Z>>>7,Q=($>>>1|Z<<31)^($>>>8|Z<<24)^($>>>7|Z<<25),te=u[X-2],ee=te.high,re=te.low,ie=(ee>>>19|re<<13)^(ee<<3|re>>>29)^ee>>>6,ne=(re>>>19|ee<<13)^(re<<3|ee>>>29)^(re>>>6|ee<<26),se=u[X-7],oe=se.high,ae=se.low,he=u[X-16],ue=he.high,ge=he.low,z=Q+ae,q=Y+oe+(Q>>>0>z>>>0?1:0),z=z+ne,q=q+ie+(ne>>>0>z>>>0?1:0),z=z+ge,q=q+ue+(ge>>>0>z>>>0?1:0);V.high=q,V.low=z}var ce=M&K^~M&k,pe=J&U^~J&L,fe=E&T^E&N^T&N,le=P&O^P&C^O&C,de=(E>>>28|P<<4)^(E<<30|P>>>2)^(E<<25|P>>>7),ye=(P>>>28|E<<4)^(P<<30|E>>>2)^(P<<25|E>>>7),ve=(M>>>14|J<<18)^(M>>>18|J<<14)^(M<<23|J>>>9),Se=(J>>>14|M<<18)^(J>>>18|M<<14)^(J<<23|M>>>9),be=h[X],me=be.high,Ae=be.low,_e=F+Se,we=W+ve+(F>>>0>_e>>>0?1:0),_e=_e+pe,we=we+ce+(pe>>>0>_e>>>0?1:0),_e=_e+Ae,we=we+me+(Ae>>>0>_e>>>0?1:0),_e=_e+z,we=we+q+(z>>>0>_e>>>0?1:0),xe=ye+le,Re=de+fe+(ye>>>0>xe>>>0?1:0);W=k,F=L,k=K,L=U,K=M,U=J,J=j+_e|0,M=D+we+(j>>>0>J>>>0?1:0)|0,D=N,j=C,N=T,C=O,T=E,O=P,P=_e+xe|0,E=we+Re+(_e>>>0>P>>>0?1:0)|0}l=i.low=l+P,i.high=f+E+(P>>>0>l>>>0?1:0),y=n.low=y+O,n.high=d+T+(O>>>0>y>>>0?1:0),S=s.low=S+C,s.high=v+N+(C>>>0>S>>>0?1:0),m=o.low=m+j,o.high=b+D+(j>>>0>m>>>0?1:0),_=a.low=_+J,a.high=A+M+(J>>>0>_>>>0?1:0),x=g.low=x+U,g.high=w+K+(U>>>0>x>>>0?1:0),H=c.low=H+L,c.high=R+k+(L>>>0>H>>>0?1:0),I=p.low=I+F,p.high=B+W+(F>>>0>I>>>0?1:0)},_doFinalize:function(){var t=this._data,e=t.words,r=8*this._nDataBytes,i=8*t.sigBytes;e[i>>>5]|=128<<24-i%32,e[(i+128>>>10<<5)+30]=Math.floor(r/4294967296),e[(i+128>>>10<<5)+31]=r,t.sigBytes=4*e.length,this._process();var n=this._hash.toX32();return n},clone:function(){var t=i.clone.call(this);return t._hash=this._hash.clone(),t},blockSize:32});e.SHA512=i._createHelper(g),e.HmacSHA512=i._createHmacHelper(g)}();var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="=",dbits,canary=0xdeadbeefcafe,j_lm=15715070==(16777215&canary);j_lm&&"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=am2,dbits=30):j_lm&&"Netscape"!=navigator.appName?(BigInteger.prototype.am=am1,dbits=26):(BigInteger.prototype.am=am3,dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<=vv;++vv)BI_RC[rr++]=vv;for(rr="a".charCodeAt(0),vv=10;36>vv;++vv)BI_RC[rr++]=vv;for(rr="A".charCodeAt(0),vv=10;36>vv;++vv)BI_RC[rr++]=vv;Classic.prototype.convert=cConvert,Classic.prototype.revert=cRevert,Classic.prototype.reduce=cReduce,Classic.prototype.mulTo=cMulTo,Classic.prototype.sqrTo=cSqrTo,Montgomery.prototype.convert=montConvert,Montgomery.prototype.revert=montRevert,Montgomery.prototype.reduce=montReduce,Montgomery.prototype.mulTo=montMulTo,Montgomery.prototype.sqrTo=montSqrTo,BigInteger.prototype.copyTo=bnpCopyTo,BigInteger.prototype.fromInt=bnpFromInt,BigInteger.prototype.fromString=bnpFromString,BigInteger.prototype.clamp=bnpClamp,BigInteger.prototype.dlShiftTo=bnpDLShiftTo,BigInteger.prototype.drShiftTo=bnpDRShiftTo,BigInteger.prototype.lShiftTo=bnpLShiftTo,BigInteger.prototype.rShiftTo=bnpRShiftTo,BigInteger.prototype.subTo=bnpSubTo,BigInteger.prototype.multiplyTo=bnpMultiplyTo,BigInteger.prototype.squareTo=bnpSquareTo,BigInteger.prototype.divRemTo=bnpDivRemTo,BigInteger.prototype.invDigit=bnpInvDigit,BigInteger.prototype.isEven=bnpIsEven,BigInteger.prototype.exp=bnpExp,BigInteger.prototype.toString=bnToString,BigInteger.prototype.negate=bnNegate,BigInteger.prototype.abs=bnAbs,BigInteger.prototype.compareTo=bnCompareTo,BigInteger.prototype.bitLength=bnBitLength,BigInteger.prototype.mod=bnMod,BigInteger.prototype.modPowInt=bnModPowInt,BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1),NullExp.prototype.convert=nNop,NullExp.prototype.revert=nNop,NullExp.prototype.mulTo=nMulTo,NullExp.prototype.sqrTo=nSqrTo,Barrett.prototype.convert=barrettConvert,Barrett.prototype.revert=barrettRevert,Barrett.prototype.reduce=barrettReduce,Barrett.prototype.mulTo=barrettMulTo,Barrett.prototype.sqrTo=barrettSqrTo;var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=(1<<26)/lowprimes[lowprimes.length-1];BigInteger.prototype.chunkSize=bnpChunkSize,BigInteger.prototype.toRadix=bnpToRadix,BigInteger.prototype.fromRadix=bnpFromRadix,BigInteger.prototype.fromNumber=bnpFromNumber,BigInteger.prototype.bitwiseTo=bnpBitwiseTo,BigInteger.prototype.changeBit=bnpChangeBit,BigInteger.prototype.addTo=bnpAddTo,BigInteger.prototype.dMultiply=bnpDMultiply,BigInteger.prototype.dAddOffset=bnpDAddOffset,BigInteger.prototype.multiplyLowerTo=bnpMultiplyLowerTo,BigInteger.prototype.multiplyUpperTo=bnpMultiplyUpperTo,BigInteger.prototype.modInt=bnpModInt,BigInteger.prototype.millerRabin=bnpMillerRabin,BigInteger.prototype.clone=bnClone,BigInteger.prototype.intValue=bnIntValue,BigInteger.prototype.byteValue=bnByteValue,BigInteger.prototype.shortValue=bnShortValue,BigInteger.prototype.signum=bnSigNum,BigInteger.prototype.toByteArray=bnToByteArray,BigInteger.prototype.equals=bnEquals,BigInteger.prototype.min=bnMin,BigInteger.prototype.max=bnMax,BigInteger.prototype.and=bnAnd,BigInteger.prototype.or=bnOr,BigInteger.prototype.xor=bnXor,BigInteger.prototype.andNot=bnAndNot,BigInteger.prototype.not=bnNot,BigInteger.prototype.shiftLeft=bnShiftLeft,BigInteger.prototype.shiftRight=bnShiftRight,BigInteger.prototype.getLowestSetBit=bnGetLowestSetBit,BigInteger.prototype.bitCount=bnBitCount,BigInteger.prototype.testBit=bnTestBit,BigInteger.prototype.setBit=bnSetBit,BigInteger.prototype.clearBit=bnClearBit,BigInteger.prototype.flipBit=bnFlipBit,BigInteger.prototype.add=bnAdd,BigInteger.prototype.subtract=bnSubtract,BigInteger.prototype.multiply=bnMultiply,BigInteger.prototype.divide=bnDivide,BigInteger.prototype.remainder=bnRemainder,BigInteger.prototype.divideAndRemainder=bnDivideAndRemainder,BigInteger.prototype.modPow=bnModPow,BigInteger.prototype.modInverse=bnModInverse,BigInteger.prototype.pow=bnPow,BigInteger.prototype.gcd=bnGCD,BigInteger.prototype.isProbablePrime=bnIsProbablePrime,BigInteger.prototype.square=bnSquare;var SHA1_SIZE=20;RSAKey.prototype.doPublic=RSADoPublic,RSAKey.prototype.setPublic=RSASetPublic,RSAKey.prototype.encrypt=RSAEncrypt,RSAKey.prototype.encryptOAEP=RSAEncryptOAEP,RSAKey.prototype.type="RSA";var SHA1_SIZE=20;RSAKey.prototype.doPrivate=RSADoPrivate,RSAKey.prototype.setPrivate=RSASetPrivate,RSAKey.prototype.setPrivateEx=RSASetPrivateEx,RSAKey.prototype.generate=RSAGenerate,RSAKey.prototype.decrypt=RSADecrypt,RSAKey.prototype.decryptOAEP=RSADecryptOAEP,RSAKey.prototype.readPrivateKeyFromPEMString=_rsapem_readPrivateKeyFromPEMString,RSAKey.prototype.readPrivateKeyFromASN1HexString=_rsapem_readPrivateKeyFromASN1HexString;var _RE_HEXDECONLY=new RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi"),RSAKey.prototype.signWithMessageHash=_rsasign_signWithMessageHash,RSAKey.prototype.signString=_rsasign_signString,RSAKey.prototype.signStringWithSHA1=_rsasign_signStringWithSHA1,RSAKey.prototype.signStringWithSHA256=_rsasign_signStringWithSHA256,RSAKey.prototype.sign=_rsasign_signString,RSAKey.prototype.signWithSHA1=_rsasign_signStringWithSHA1,RSAKey.prototype.signWithSHA256=_rsasign_signStringWithSHA256,RSAKey.prototype.signWithMessageHashPSS=_rsasign_signWithMessageHashPSS,RSAKey.prototype.signStringPSS=_rsasign_signStringPSS,RSAKey.prototype.signPSS=_rsasign_signStringPSS,RSAKey.SALT_LEN_HLEN=-1,RSAKey.SALT_LEN_MAX=-2,RSAKey.prototype.verifyWithMessageHash=_rsasign_verifyWithMessageHash,RSAKey.prototype.verifyString=_rsasign_verifyString,RSAKey.prototype.verifyHexSignatureForMessage=_rsasign_verifyHexSignatureForMessage,RSAKey.prototype.verify=_rsasign_verifyString,RSAKey.prototype.verifyHexSignatureForByteArrayMessage=_rsasign_verifyHexSignatureForMessage,RSAKey.prototype.verifyWithMessageHashPSS=_rsasign_verifyWithMessageHashPSS,RSAKey.prototype.verifyStringPSS=_rsasign_verifyStringPSS,RSAKey.prototype.verifyPSS=_rsasign_verifyStringPSS,RSAKey.SALT_LEN_RECOVER=-2;var ASN1HEX=new function(){this.getByteLengthOfL_AtObj=function(t,e){if("8"!=t.substring(e+2,e+3))return 1;var r=parseInt(t.substring(e+3,e+4));return 0==r?-1:r>0&&10>r?r+1:-2},this.getHexOfL_AtObj=function(t,e){var r=this.getByteLengthOfL_AtObj(t,e);return 1>r?"":t.substring(e+2,e+2+2*r)},this.getIntOfL_AtObj=function(t,e){var r=this.getHexOfL_AtObj(t,e);if(""==r)return-1;var i;return i=parseInt(r.substring(0,1))<8?new BigInteger(r,16):new BigInteger(r.substring(2),16),i.intValue()},this.getStartPosOfV_AtObj=function(t,e){var r=this.getByteLengthOfL_AtObj(t,e);return 0>r?r:e+2*(r+1)},this.getHexOfV_AtObj=function(t,e){var r=this.getStartPosOfV_AtObj(t,e),i=this.getIntOfL_AtObj(t,e);return t.substring(r,r+2*i)},this.getHexOfTLV_AtObj=function(t,e){var r=t.substr(e,2),i=this.getHexOfL_AtObj(t,e),n=this.getHexOfV_AtObj(t,e);return r+i+n},this.getPosOfNextSibling_AtObj=function(t,e){var r=this.getStartPosOfV_AtObj(t,e),i=this.getIntOfL_AtObj(t,e);return r+2*i},this.getPosArrayOfChildren_AtObj=function(t,e){var r=new Array,i=this.getStartPosOfV_AtObj(t,e);r.push(i);for(var n=this.getIntOfL_AtObj(t,e),s=i,o=0;;){var a=this.getPosOfNextSibling_AtObj(t,s);if(null==a||a-i>=2*n)break;if(o>=200)break;r.push(a),s=a,o++}return r},this.getNthChildIndex_AtObj=function(t,e,r){var i=this.getPosArrayOfChildren_AtObj(t,e);return i[r]},this.getDecendantIndexByNthList=function(t,e,r){if(0==r.length)return e;var i=r.shift(),n=this.getPosArrayOfChildren_AtObj(t,e);return this.getDecendantIndexByNthList(t,n[i],r)},this.getDecendantHexTLVByNthList=function(t,e,r){var i=this.getDecendantIndexByNthList(t,e,r);return this.getHexOfTLV_AtObj(t,i)},this.getDecendantHexVByNthList=function(t,e,r){var i=this.getDecendantIndexByNthList(t,e,r);return this.getHexOfV_AtObj(t,i)}};ASN1HEX.getVbyList=function(t,e,r,i){var n=this.getDecendantIndexByNthList(t,e,r);if(void 0===n)throw"can't find nthList object";if(void 0!==i&&t.substr(n,2)!=i)throw"checking tag doesn't match: "+t.substr(n,2)+"!="+i;return this.getHexOfV_AtObj(t,n)},ASN1HEX.hextooidstr=function(t){var e=function(t,e){return t.length>=e?t:new Array(e-t.length+1).join("0")+t},r=[],i=t.substr(0,2),n=parseInt(i,16);r[0]=new String(Math.floor(n/40)),r[1]=new String(n%40);for(var s=t.substr(2),o=[],a=0;a0&&(g=g+"."+h.join(".")),g},X509.pemToBase64=function(t){var e=t;return e=e.replace("-----BEGIN CERTIFICATE-----",""),e=e.replace("-----END CERTIFICATE-----",""),e=e.replace(/[ \n]+/g,"")},X509.pemToHex=function(t){var e=X509.pemToBase64(t),r=b64tohex(e);return r},X509.getSubjectPublicKeyPosFromCertHex=function(t){var e=X509.getSubjectPublicKeyInfoPosFromCertHex(t);if(-1==e)return-1;var r=ASN1HEX.getPosArrayOfChildren_AtObj(t,e);if(2!=r.length)return-1;var i=r[1];if("03"!=t.substring(i,i+2))return-1;var n=ASN1HEX.getStartPosOfV_AtObj(t,i);return"00"!=t.substring(n,n+2)?-1:n+2},X509.getSubjectPublicKeyInfoPosFromCertHex=function(t){var e=ASN1HEX.getStartPosOfV_AtObj(t,0),r=ASN1HEX.getPosArrayOfChildren_AtObj(t,e);return r.length<1?-1:"a003020102"==t.substring(r[0],r[0]+10)?r.length<6?-1:r[6]:r.length<5?-1:r[5]},X509.getPublicKeyHexArrayFromCertHex=function(t){var e=X509.getSubjectPublicKeyPosFromCertHex(t),r=ASN1HEX.getPosArrayOfChildren_AtObj(t,e);if(2!=r.length)return[];var i=ASN1HEX.getHexOfV_AtObj(t,r[0]),n=ASN1HEX.getHexOfV_AtObj(t,r[1]);return null!=i&&null!=n?[i,n]:[]},X509.getHexTbsCertificateFromCert=function(t){var e=ASN1HEX.getStartPosOfV_AtObj(t,0);return e},X509.getPublicKeyHexArrayFromCertPEM=function(t){var e=X509.pemToHex(t),r=X509.getPublicKeyHexArrayFromCertHex(e);return r},X509.hex2dn=function(t){for(var e="",r=ASN1HEX.getPosArrayOfChildren_AtObj(t,0),i=0;in)throw"key is too short for SigAlg: keylen="+r+","+e;for(var s="0001",o="00"+i,a="",h=n-s.length-o.length,u=0;h>u;u+=2)a+="ff";var g=s+a+o;return g},this.hashString=function(t,e){var r=new KJUR.crypto.MessageDigest({alg:e});return r.digestString(t)},this.hashHex=function(t,e){var r=new KJUR.crypto.MessageDigest({alg:e});return r.digestHex(t)},this.sha1=function(t){var e=new KJUR.crypto.MessageDigest({alg:"sha1",prov:"cryptojs"});return e.digestString(t)},this.sha256=function(t){var e=new KJUR.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"});return e.digestString(t)},this.sha256Hex=function(t){var e=new KJUR.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"});return e.digestHex(t)},this.sha512=function(t){var e=new KJUR.crypto.MessageDigest({alg:"sha512",prov:"cryptojs"});return e.digestString(t)},this.sha512Hex=function(t){var e=new KJUR.crypto.MessageDigest({alg:"sha512",prov:"cryptojs"});return e.digestHex(t)},this.md5=function(t){var e=new KJUR.crypto.MessageDigest({alg:"md5",prov:"cryptojs"});return e.digestString(t)},this.ripemd160=function(t){var e=new KJUR.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"});return e.digestString(t)},this.getCryptoJSMDByName=function(){}},KJUR.crypto.MessageDigest=function(params){var md=null,algName=null,provName=null;this.setAlgAndProvider=function(alg,prov){if(null!=alg&&void 0===prov&&(prov=KJUR.crypto.Util.DEFAULTPROVIDER[alg]),-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(alg)&&"cryptojs"==prov){try{this.md=eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[alg]).create()}catch(ex){throw"setAlgAndProvider hash alg set fail alg="+alg+"/"+ex}this.updateString=function(t){this.md.update(t)},this.updateHex=function(t){var e=CryptoJS.enc.Hex.parse(t);this.md.update(e)},this.digest=function(){var t=this.md.finalize();return t.toString(CryptoJS.enc.Hex)},this.digestString=function(t){return this.updateString(t),this.digest()},this.digestHex=function(t){return this.updateHex(t),this.digest()}}if(-1!=":sha256:".indexOf(alg)&&"sjcl"==prov){try{this.md=new sjcl.hash.sha256}catch(ex){throw"setAlgAndProvider hash alg set fail alg="+alg+"/"+ex}this.updateString=function(t){this.md.update(t)},this.updateHex=function(t){var e=sjcl.codec.hex.toBits(t);this.md.update(e)},this.digest=function(){var t=this.md.finalize();return sjcl.codec.hex.fromBits(t)},this.digestString=function(t){return this.updateString(t),this.digest()},this.digestHex=function(t){return this.updateHex(t),this.digest()}}},this.updateString=function(){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},void 0!==params&&void 0!==params.alg&&(this.algName=params.alg,void 0===params.prov&&(this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)) -},KJUR.crypto.Mac=function(params){var mac=null,pass=null,algName=null,provName=null,algProv=null;this.setAlgAndProvider=function(alg,prov){if(null==alg&&(alg="hmacsha1"),alg=alg.toLowerCase(),"hmac"!=alg.substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+alg;void 0===prov&&(prov=KJUR.crypto.Util.DEFAULTPROVIDER[alg]),this.algProv=alg+"/"+prov;var hashAlg=alg.substr(4);if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(hashAlg)&&"cryptojs"==prov){try{var mdObj=eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[hashAlg]);this.mac=CryptoJS.algo.HMAC.create(mdObj,this.pass)}catch(ex){throw"setAlgAndProvider hash alg set fail hashAlg="+hashAlg+"/"+ex}this.updateString=function(t){this.mac.update(t)},this.updateHex=function(t){var e=CryptoJS.enc.Hex.parse(t);this.mac.update(e)},this.doFinal=function(){var t=this.mac.finalize();return t.toString(CryptoJS.enc.Hex)},this.doFinalString=function(t){return this.updateString(t),this.doFinal()},this.doFinalHex=function(t){return this.updateHex(t),this.doFinal()}}},this.updateString=function(){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},void 0!==params&&(void 0!==params.pass&&(this.pass=params.pass),void 0!==params.alg&&(this.algName=params.alg,void 0===params.prov&&(this.provName=KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},KJUR.crypto.Signature=function(t){var e=null;if(this._setAlgNames=function(){this.algName.match(/^(.+)with(.+)$/)&&(this.mdAlgName=RegExp.$1.toLowerCase(),this.pubkeyAlgName=RegExp.$2.toLowerCase())},this._zeroPaddingOfSignature=function(t,e){for(var r="",i=e/4-t.length,n=0;i>n;n++)r+="0";return r+t},this.setAlgAndProvider=function(t,e){if(this._setAlgNames(),"cryptojs/jsrsa"!=e)throw"provider not supported: "+e;if(-1!=":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)){try{this.md=new KJUR.crypto.MessageDigest({alg:this.mdAlgName})}catch(r){throw"setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+r}this.init=function(t,e){var r=null;try{r=void 0===e?KEYUTIL.getKey(t):KEYUTIL.getKey(t,e)}catch(i){throw"init failed:"+i}if(r.isPrivate===!0)this.prvKey=r,this.state="SIGN";else{if(r.isPublic!==!0)throw"init failed.:"+r;this.pubKey=r,this.state="VERIFY"}},this.initSign=function(t){"string"==typeof t.ecprvhex&&"string"==typeof t.eccurvename?(this.ecprvhex=t.ecprvhex,this.eccurvename=t.eccurvename):this.prvKey=t,this.state="SIGN"},this.initVerifyByPublicKey=function(t){"string"==typeof t.ecpubhex&&"string"==typeof t.eccurvename?(this.ecpubhex=t.ecpubhex,this.eccurvename=t.eccurvename):t instanceof KJUR.crypto.ECDSA?this.pubKey=t:t instanceof RSAKey&&(this.pubKey=t),this.state="VERIFY"},this.initVerifyByCertificatePEM=function(t){var e=new X509;e.readCertPEM(t),this.pubKey=e.subjectPublicKeyRSA,this.state="VERIFY"},this.updateString=function(t){this.md.updateString(t)},this.updateHex=function(t){this.md.updateHex(t)},this.sign=function(){if(this.sHashHex=this.md.digest(),"undefined"!=typeof this.ecprvhex&&"undefined"!=typeof this.eccurvename){var t=new KJUR.crypto.ECDSA({curve:this.eccurvename});this.hSign=t.signHex(this.sHashHex,this.ecprvhex)}else if("rsaandmgf1"==this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if("rsa"==this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof KJUR.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof KJUR.crypto.DSA))throw"Signature: unsupported public key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(t){return this.updateString(t),this.sign()},this.signHex=function(t){return this.updateHex(t),this.sign()},this.verify=function(t){if(this.sHashHex=this.md.digest(),"undefined"!=typeof this.ecpubhex&&"undefined"!=typeof this.eccurvename){var e=new KJUR.crypto.ECDSA({curve:this.eccurvename});return e.verifyHex(this.sHashHex,t,this.ecpubhex)}if("rsaandmgf1"==this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,t,this.mdAlgName,this.pssSaltLen);if("rsa"==this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,t);if(this.pubKey instanceof KJUR.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,t);if(this.pubKey instanceof KJUR.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,t);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.initVerifyByPublicKey=function(){throw"initVerifyByPublicKey(rsaPubKeyy) not supported for this alg:prov="+this.algProvName},this.initVerifyByCertificatePEM=function(){throw"initVerifyByCertificatePEM(certPEM) not supported for this alg:prov="+this.algProvName},this.initSign=function(){throw"initSign(prvKey) not supported for this alg:prov="+this.algProvName},this.updateString=function(){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=t,void 0!==t&&(void 0!==t.alg&&(this.algName=t.alg,this.provName=void 0===t.prov?KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]:t.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==t.psssaltlen&&(this.pssSaltLen=t.psssaltlen),void 0!==t.prvkeypem)){if(void 0!==t.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";try{var e=new RSAKey;e.readPrivateKeyFromPEMString(t.prvkeypem),this.initSign(e)}catch(r){throw"fatal error to load pem private key: "+r}}},KJUR.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}};var utf8tob64u,b64utoutf8;"function"==typeof Buffer?(utf8tob64u=function(t){return b64tob64u(new Buffer(t,"utf8").toString("base64"))},b64utoutf8=function(t){return new Buffer(b64utob64(t),"base64").toString("utf8")}):(utf8tob64u=function(t){return hextob64u(uricmptohex(encodeURIComponentAll(t)))},b64utoutf8=function(t){return decodeURIComponent(hextouricmp(b64utohex(t)))});var jsonParse=function(){function t(t,e,r){return e?o[e]:String.fromCharCode(parseInt(r,16))}var e="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",r='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))',i='(?:"'+r+'*")',n=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+e+"|"+i+")","g"),s=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),o={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:" "},a=new String(""),h="\\",u=({"{":Object,"[":Array},Object.hasOwnProperty);return function(e,r){var i,o=e.match(n),g=o[0],c=!1;"{"===g?i={}:"["===g?i=[]:(i=[],c=!0);for(var p,f=[i],l=1-c,d=o.length;d>l;++l){g=o[l];var y;switch(g.charCodeAt(0)){default:y=f[0],y[p||y.length]=+g,p=void 0;break;case 34:if(g=g.substring(1,g.length-1),-1!==g.indexOf(h)&&(g=g.replace(s,t)),y=f[0],!p){if(!(y instanceof Array)){p=g||a;break}p=y.length}y[p]=g,p=void 0;break;case 91:y=f[0],f.unshift(y[p||y.length]=[]),p=void 0;break;case 93:f.shift();break;case 102:y=f[0],y[p||y.length]=!1,p=void 0;break;case 110:y=f[0],y[p||y.length]=null,p=void 0;break;case 116:y=f[0],y[p||y.length]=!0,p=void 0;break;case 123:y=f[0],f.unshift(y[p||y.length]={}),p=void 0;break;case 125:f.shift()}}if(c){if(1!==f.length)throw new Error;i=i[0]}else if(f.length)throw new Error;if(r){var v=function(t,e){var i=t[e];if(i&&"object"==typeof i){var n=null;for(var s in i)if(u.call(i,s)&&i!==t){var o=v(i,s);void 0!==o?i[s]=o:(n||(n=[]),n.push(s))}if(n)for(var a=n.length;--a>=0;)delete i[n[a]]}return r.call(t,e,i)};i=v({"":i},"")}return i}}();"undefined"!=typeof KJUR&&KJUR||(KJUR={}),"undefined"!=typeof KJUR.jws&&KJUR.jws||(KJUR.jws={}),KJUR.jws.JWS=function(){function t(t,e){return utf8tob64u(t)+"."+utf8tob64u(e)}function e(t){var e=t.alg,r="";if("RS256"!=e&&"RS512"!=e&&"PS256"!=e&&"PS512"!=e)throw"JWS signature algorithm not supported: "+e;return"256"==e.substr(2)&&(r="sha256"),"512"==e.substr(2)&&(r="sha512"),r}function r(t){return e(jsonParse(t))}function i(t,e,i,n,s,o){var a=new RSAKey;a.setPrivate(n,s,o);var h=r(t),u=a.signString(i,h);return u}function n(t,i,n,s,o){var a=null;a="undefined"==typeof o?r(t):e(o);var h="PS"==o.alg.substr(0,2);return s.hashAndSign?b64tob64u(s.hashAndSign(a,n,"binary","base64",h)):hextob64u(h?s.signStringPSS(n,a):s.signString(n,a))}function s(t,e,i,n){var s=new RSAKey;s.readPrivateKeyFromPEMString(n);var o=r(t),a=s.signString(i,o);return a}this.parseJWS=function(t,e){if(void 0===this.parsedJWS||!e&&void 0===this.parsedJWS.sigvalH){if(null==t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/))throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var r=RegExp.$1,i=RegExp.$2,n=RegExp.$3,s=r+"."+i;if(this.parsedJWS={},this.parsedJWS.headB64U=r,this.parsedJWS.payloadB64U=i,this.parsedJWS.sigvalB64U=n,this.parsedJWS.si=s,!e){var o=b64utohex(n),a=parseBigInt(o,16);this.parsedJWS.sigvalH=o,this.parsedJWS.sigvalBI=a}var h=b64utoutf8(r),u=b64utoutf8(i);if(this.parsedJWS.headS=h,this.parsedJWS.payloadS=u,!KJUR.jws.JWS.isSafeJSONString(h,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+h}},this.verifyJWSByNE=function(t,e,r){return this.parseJWS(t),_rsasign_verifySignatureWithArgs(this.parsedJWS.si,this.parsedJWS.sigvalBI,e,r)},this.verifyJWSByKey=function(t,r){this.parseJWS(t);var i=e(this.parsedJWS.headP),n="PS"==this.parsedJWS.headP.alg.substr(0,2);return r.hashAndVerify?r.hashAndVerify(i,new Buffer(this.parsedJWS.si,"utf8").toString("base64"),b64utob64(this.parsedJWS.sigvalB64U),"base64",n):n?r.verifyStringPSS(this.parsedJWS.si,this.parsedJWS.sigvalH,i):r.verifyString(this.parsedJWS.si,this.parsedJWS.sigvalH)},this.verifyJWSByPemX509Cert=function(t,e){this.parseJWS(t);var r=new X509;return r.readCertPEM(e),r.subjectPublicKeyRSA.verifyString(this.parsedJWS.si,this.parsedJWS.sigvalH)},this.generateJWSByNED=function(e,r,n,s,o){if(!KJUR.jws.JWS.isSafeJSONString(e))throw"JWS Head is not safe JSON string: "+e;var a=t(e,r),h=i(e,r,a,n,s,o),u=hextob64u(h);return this.parsedJWS={},this.parsedJWS.headB64U=a.split(".")[0],this.parsedJWS.payloadB64U=a.split(".")[1],this.parsedJWS.sigvalB64U=u,a+"."+u},this.generateJWSByKey=function(e,r,i){var s={};if(!KJUR.jws.JWS.isSafeJSONString(e,s,"headP"))throw"JWS Head is not safe JSON string: "+e;var o=t(e,r),a=n(e,r,o,i,s.headP);return this.parsedJWS={},this.parsedJWS.headB64U=o.split(".")[0],this.parsedJWS.payloadB64U=o.split(".")[1],this.parsedJWS.sigvalB64U=a,o+"."+a},this.generateJWSByP1PrvKey=function(e,r,i){if(!KJUR.jws.JWS.isSafeJSONString(e))throw"JWS Head is not safe JSON string: "+e;var n=t(e,r),o=s(e,r,n,i),a=hextob64u(o);return this.parsedJWS={},this.parsedJWS.headB64U=n.split(".")[0],this.parsedJWS.payloadB64U=n.split(".")[1],this.parsedJWS.sigvalB64U=a,n+"."+a}},KJUR.jws.JWS.sign=function(t,e,r,i,n){var s=KJUR.jws.JWS;if(!s.isSafeJSONString(e))throw"JWS Head is not safe JSON string: "+sHead;var o=s.readSafeJSONString(e);""!=t&&null!=t||void 0===o.alg||(t=o.alg),""!=t&&null!=t&&void 0===o.alg&&(o.alg=t,e=JSON.stringify(o));var a=null;if(void 0===s.jwsalg2sigalg[t])throw"unsupported alg name: "+t;a=s.jwsalg2sigalg[t];var h=utf8tob64u(e),u=utf8tob64u(r),g=h+"."+u,c="";if("Hmac"==a.substr(0,4)){if(void 0===i)throw"hexadecimal key shall be specified for HMAC";var p=new KJUR.crypto.Mac({alg:a,pass:hextorstr(i)});p.updateString(g),c=p.doFinal()}else if(-1!=a.indexOf("withECDSA")){var f=new KJUR.crypto.Signature({alg:a});f.init(i,n),f.updateString(g),hASN1Sig=f.sign(),c=KJUR.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig)}else if("none"!=a){var f=new KJUR.crypto.Signature({alg:a});f.init(i,n),f.updateString(g),c=f.sign()}var l=hextob64u(c);return g+"."+l},KJUR.jws.JWS.verify=function(t,e){var r=KJUR.jws.JWS,i=t.split("."),n=i[0],s=i[1],o=n+"."+s,a=b64utohex(i[2]),h=r.readSafeJSONString(b64utoutf8(i[0])),u=null;if(void 0===h.alg)throw"algorithm not specified in header";u=h.alg;var g=null;if(void 0===r.jwsalg2sigalg[h.alg])throw"unsupported alg name: "+u;if(g=r.jwsalg2sigalg[u],"none"==g)return!0;if("Hmac"==g.substr(0,4)){if(void 0===e)throw"hexadecimal key shall be specified for HMAC";var c=new KJUR.crypto.Mac({alg:g,pass:hextorstr(e)});return c.updateString(o),hSig2=c.doFinal(),a==hSig2}if(-1!=g.indexOf("withECDSA")){var p=null;try{p=KJUR.crypto.ECDSA.concatSigToASN1Sig(a)}catch(f){return!1}var l=new KJUR.crypto.Signature({alg:g});return l.init(e),l.updateString(o),l.verify(p)}var l=new KJUR.crypto.Signature({alg:g});return l.init(e),l.updateString(o),l.verify(a)},KJUR.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},KJUR.jws.JWS.isSafeJSONString=function(t,e,r){var i=null;try{return i=jsonParse(t),"object"!=typeof i?0:i.constructor===Array?0:(e&&(e[r]=i),1)}catch(n){return 0}},KJUR.jws.JWS.readSafeJSONString=function(t){var e=null;try{return e=jsonParse(t),"object"!=typeof e?null:e.constructor===Array?null:e}catch(r){return null}},KJUR.jws.JWS.getEncodedSignatureValueFromJWS=function(t){if(null==t.match(/^[^.]+\.[^.]+\.([^.]+)$/))throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return RegExp.$1},KJUR.jws.IntDate=function(){},KJUR.jws.IntDate.get=function(t){if("now"==t)return KJUR.jws.IntDate.getNow();if("now + 1hour"==t)return KJUR.jws.IntDate.getNow()+3600;if("now + 1day"==t)return KJUR.jws.IntDate.getNow()+86400;if("now + 1month"==t)return KJUR.jws.IntDate.getNow()+2592e3;if("now + 1year"==t)return KJUR.jws.IntDate.getNow()+31536e3;if(t.match(/Z$/))return KJUR.jws.IntDate.getZulu(t);if(t.match(/^[0-9]+$/))return parseInt(t);throw"unsupported format: "+t},KJUR.jws.IntDate.getZulu=function(t){if(a=t.match(/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z/)){var e=parseInt(RegExp.$1),r=parseInt(RegExp.$2)-1,i=parseInt(RegExp.$3),n=parseInt(RegExp.$4),s=parseInt(RegExp.$5),o=parseInt(RegExp.$6),h=new Date(Date.UTC(e,r,i,n,s,o));return~~(h/1e3)}throw"unsupported format: "+t},KJUR.jws.IntDate.getNow=function(){var t=~~(new Date/1e3);return t},KJUR.jws.IntDate.intDate2UTCString=function(t){var e=new Date(1e3*t);return e.toUTCString()},KJUR.jws.IntDate.intDate2Zulu=function(t){var e=new Date(1e3*t),r=("0000"+e.getUTCFullYear()).slice(-4),i=("00"+(e.getUTCMonth()+1)).slice(-2),n=("00"+e.getUTCDate()).slice(-2),s=("00"+e.getUTCHours()).slice(-2),o=("00"+e.getUTCMinutes()).slice(-2),a=("00"+e.getUTCSeconds()).slice(-2);return r+i+n+s+o+a+"Z"},function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function r(t){return"object"==typeof t&&null!==t}function i(t){k=t}function n(t){X=t}function s(){return function(){process.nextTick(g)}}function o(){return function(){U(g)}}function a(){var t=0,e=new z(g),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){r.data=t=++t%2}}function h(){var t=new MessageChannel;return t.port1.onmessage=g,function(){t.port2.postMessage(0)}}function u(){return function(){setTimeout(g,1)}}function g(){for(var t=0;F>t;t+=2){var e=$[t],r=$[t+1];e(r),$[t]=void 0,$[t+1]=void 0}F=0}function c(){try{var t=require,e=t("vertx");return U=e.runOnLoop||e.runOnContext,o()}catch(r){return u()}}function p(){}function f(){return new TypeError("You cannot resolve a promise with itself")}function l(){return new TypeError("A promises callback cannot return that same promise.")}function d(t){try{return t.then}catch(e){return ee.error=e,ee}}function y(t,e,r,i){try{t.call(e,r,i)}catch(n){return n}}function v(t,e,r){X(function(t){var i=!1,n=y(r,e,function(r){i||(i=!0,e!==r?m(t,r):_(t,r))},function(e){i||(i=!0,w(t,e))},"Settle: "+(t._label||" unknown promise"));!i&&n&&(i=!0,w(t,n))},t)}function S(t,e){e._state===Q?_(t,e._result):e._state===te?w(t,e._result):x(e,void 0,function(e){m(t,e)},function(e){w(t,e)})}function b(t,r){if(r.constructor===t.constructor)S(t,r);else{var i=d(r);i===ee?w(t,ee.error):void 0===i?_(t,r):e(i)?v(t,r,i):_(t,r)}}function m(e,r){e===r?w(e,f()):t(r)?b(e,r):_(e,r)}function A(t){t._onerror&&t._onerror(t._result),R(t)}function _(t,e){t._state===Y&&(t._result=e,t._state=Q,0!==t._subscribers.length&&X(R,t))}function w(t,e){t._state===Y&&(t._state=te,t._result=e,X(A,t))}function x(t,e,r,i){var n=t._subscribers,s=n.length;t._onerror=null,n[s]=e,n[s+Q]=r,n[s+te]=i,0===s&&t._state&&X(R,t)}function R(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var i,n,s=t._result,o=0;oo;o++)x(i.resolve(t[o]),void 0,e,r);return n}function N(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var r=new e(p);return m(r,t),r}function C(t){var e=this,r=new e(p);return w(r,t),r}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function j(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function M(t){this._id=he++,this._state=void 0,this._result=void 0,this._subscribers=[],p!==t&&(e(t)||D(),this instanceof M||j(),E(this,t))}function J(){var t;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var r=t.Promise;(!r||"[object Promise]"!==Object.prototype.toString.call(r.resolve())||r.cast)&&(t.Promise=ue)}var K;K=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var U,k,L,W=K,F=0,X=({}.toString,function(t,e){$[F]=t,$[F+1]=e,F+=2,2===F&&(k?k(g):L())}),V="undefined"!=typeof window?window:void 0,q=V||{},z=q.MutationObserver||q.WebKitMutationObserver,G="undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Z="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,$=new Array(1e3);L=G?s():z?a():Z?h():void 0===V&&"function"==typeof require?c():u();var Y=void 0,Q=1,te=2,ee=new H,re=new H;P.prototype._validateInput=function(t){return W(t)},P.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},P.prototype._init=function(){this._result=new Array(this.length)};var ie=P;P.prototype._enumerate=function(){for(var t=this,e=t.length,r=t.promise,i=t._input,n=0;r._state===Y&&e>n;n++)t._eachEntry(i[n],n)},P.prototype._eachEntry=function(t,e){var i=this,n=i._instanceConstructor;r(t)?t.constructor===n&&t._state!==Y?(t._onerror=null,i._settledAt(t._state,e,t._result)):i._willSettleAt(n.resolve(t),e):(i._remaining--,i._result[e]=t)},P.prototype._settledAt=function(t,e,r){var i=this,n=i.promise;n._state===Y&&(i._remaining--,t===te?w(n,r):i._result[e]=r),0===i._remaining&&_(n,i._result)},P.prototype._willSettleAt=function(t,e){var r=this;x(t,void 0,function(t){r._settledAt(Q,e,t)},function(t){r._settledAt(te,e,t)})};var ne=T,se=O,oe=N,ae=C,he=0,ue=M;M.all=ne,M.race=se,M.resolve=oe,M.reject=ae,M._setScheduler=i,M._setAsap=n,M._asap=X,M.prototype={constructor:M,then:function(t,e){var r=this,i=r._state;if(i===Q&&!t||i===te&&!e)return this;var n=new this.constructor(p),s=r._result;if(i){var o=arguments[i-1];X(function(){I(i,n,o,s)})}else x(r,n,t,e);return n},"catch":function(t){return this.then(null,t)}};var ge=J,ce={Promise:ue,polyfill:ge};"function"==typeof define&&define.amd?define(function(){return ce}):"undefined"!=typeof module&&module.exports?module.exports=ce:"undefined"!=typeof this&&(this.ES6Promise=ce),ge()}.call(this),_httpRequest=new DefaultHttpRequest,_promiseFactory=new DefaultPromiseFactory,OidcClient.parseOidcResult=parseOidcResult,OidcClient.prototype.loadMetadataAsync=function(){log("OidcClient.loadMetadataAsync");var t=this._settings;return t.metadata?resolve(t.metadata):t.authority?getJson(t.authority).then(function(e){return t.metadata=e,e},function(t){return error("Failed to load metadata ("+t&&t.message+")")}):error("No authority configured")},OidcClient.prototype.loadX509SigningKeyAsync=function(){function t(t){if(!t.keys||!t.keys.length)return error("Signing keys empty");var e=t.keys[0];return"RSA"!==e.kty?error("Signing key not RSA"):e.x5c&&e.x5c.length?resolve(e.x5c[0]):error("RSA keys empty")}log("OidcClient.loadX509SigningKeyAsync");var e=this._settings;return e.jwks?t(e.jwks):this.loadMetadataAsync().then(function(r){return r.jwks_uri?getJson(r.jwks_uri).then(function(r){return e.jwks=r,t(r)},function(t){return error("Failed to load signing keys ("+t&&t.message+")")}):error("Metadata does not contain jwks_uri")})},OidcClient.prototype.loadUserProfile=function(t){return log("OidcClient.loadUserProfile"),this.loadMetadataAsync().then(function(e){return e.userinfo_endpoint?getJson(e.userinfo_endpoint,t):error("Metadata does not contain userinfo_endpoint")})},OidcClient.prototype.loadAuthorizationEndpoint=function(){return log("OidcClient.loadAuthorizationEndpoint"),this._settings.authorization_endpoint?resolve(this._settings.authorization_endpoint):this._settings.authority?this.loadMetadataAsync().then(function(t){return t.authorization_endpoint?t.authorization_endpoint:error("Metadata does not contain authorization_endpoint")}):error("No authorization_endpoint configured")},OidcClient.prototype.createTokenRequestAsync=function(){log("OidcClient.createTokenRequestAsync");var t=this,e=t._settings;return t.loadAuthorizationEndpoint().then(function(r){var i=rand(),n=r+"?state="+encodeURIComponent(i);if(t.isOidc){var s=rand();n+="&nonce="+encodeURIComponent(s)}var o=["client_id","redirect_uri","response_type","scope"];o.forEach(function(t){var r=e[t];r&&(n+="&"+t+"="+encodeURIComponent(r))});var a=["prompt","display","max_age","ui_locales","id_token_hint","login_hint","acr_values"];a.forEach(function(t){var r=e[t];r&&(n+="&"+t+"="+encodeURIComponent(r))});var h={oidc:t.isOidc,oauth:t.isOAuth,state:i};return s&&(h.nonce=s),e.request_state_store.setItem(e.request_state_key,JSON.stringify(h)),{request_state:h,url:n}})},OidcClient.prototype.createLogoutRequestAsync=function(t){log("OidcClient.createLogoutRequestAsync");var e=this._settings;return this.loadMetadataAsync().then(function(r){if(!r.end_session_endpoint)return error("No end_session_endpoint in metadata");var i=r.end_session_endpoint;return t&&e.post_logout_redirect_uri&&(i+="?post_logout_redirect_uri="+encodeURIComponent(e.post_logout_redirect_uri),i+="&id_token_hint="+encodeURIComponent(t)),i})},OidcClient.prototype.validateIdTokenAsync=function(t,e,r){log("OidcClient.validateIdTokenAsync");var i=this,n=i._settings;return i.loadX509SigningKeyAsync().then(function(s){var o=new KJUR.jws.JWS;if(o.verifyJWSByPemX509Cert(t,s)){var a=JSON.parse(o.parsedJWS.payloadS);return e!==a.nonce?error("Invalid nonce"):i.loadMetadataAsync().then(function(t){if(a.iss!==t.issuer)return error("Invalid issuer");if(a.aud!==n.client_id)return error("Invalid audience");var e=parseInt(Date.now()/1e3),s=e-a.iat;return s>300?error("Token issued too long ago"):a.exp>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else if (thatWords.length > 0xffff) { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } else { - // Copy all words at once - thisWords.push.apply(thisWords, thatWords); - } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; - - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, - - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); - - return clone; - }, - - /** - * Creates a word array filled with random bytes. - * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.lib.WordArray.random(16); - */ - random: function (nBytes) { - var words = []; - for (var i = 0; i < nBytes; i += 4) { - words.push((Math.random() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); - - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; - - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { - /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static - * - * @example - * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); - }, - - /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); - */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); - } - - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); - } - - return latin1Chars.join(''); - }, - - /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); - */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } - }; - - /** - * UTF-8 encoding strategy. - */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, - - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); - } - }; - - /** - * Abstract buffered block algorithm template. - * - * The property blockSize must be implemented in a concrete subtype. - * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 - */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, - - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); - } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); - } - - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } - - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } - - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); - - return clone; - }, - - _minBufferSize: 0 - }); - - /** - * Abstract hasher template. - * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) - */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, - - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); - - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, - - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } - - // Perform concrete-hasher logic - var hash = this._doFinalize(); - - return hash; - }, - - blockSize: 512/32, - - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, - - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; - } - }); - - /** - * Algorithm namespace. - */ - var C_algo = C.algo = {}; - - return C; -}(Math)); - -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Reusable object - var W = []; - - /** - * SHA-1 hash algorithm. - */ - var SHA1 = C_algo.SHA1 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476, - 0xc3d2e1f0 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Shortcut - var H = this._hash.words; - - // Working variables - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - - // Computation - for (var i = 0; i < 80; i++) { - if (i < 16) { - W[i] = M[offset + i] | 0; - } else { - var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; - W[i] = (n << 1) | (n >>> 31); - } - - var t = ((a << 5) | (a >>> 27)) + e + W[i]; - if (i < 20) { - t += ((b & c) | (~b & d)) + 0x5a827999; - } else if (i < 40) { - t += (b ^ c ^ d) + 0x6ed9eba1; - } else if (i < 60) { - t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; - } else /* if (i < 80) */ { - t += (b ^ c ^ d) - 0x359d3e2a; - } - - e = d; - d = c; - c = (b << 30) | (b >>> 2); - b = a; - a = t; - } - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - H[4] = (H[4] + e) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; - data.sigBytes = dataWords.length * 4; - - // Hash final blocks - this._process(); - - // Return final computed hash - return this._hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.SHA1('message'); - * var hash = CryptoJS.SHA1(wordArray); - */ - C.SHA1 = Hasher._createHelper(SHA1); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacSHA1(message, key); - */ - C.HmacSHA1 = Hasher._createHmacHelper(SHA1); -}()); - -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Initialization and round constants tables - var H = []; - var K = []; - - // Compute constants - (function () { - function isPrime(n) { - var sqrtN = Math.sqrt(n); - for (var factor = 2; factor <= sqrtN; factor++) { - if (!(n % factor)) { - return false; - } - } - - return true; - } - - function getFractionalBits(n) { - return ((n - (n | 0)) * 0x100000000) | 0; - } - - var n = 2; - var nPrime = 0; - while (nPrime < 64) { - if (isPrime(n)) { - if (nPrime < 8) { - H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); - } - K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); - - nPrime++; - } - - n++; - } - }()); - - // Reusable object - var W = []; - - /** - * SHA-256 hash algorithm. - */ - var SHA256 = C_algo.SHA256 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init(H.slice(0)); - }, - - _doProcessBlock: function (M, offset) { - // Shortcut - var H = this._hash.words; - - // Working variables - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - var e = H[4]; - var f = H[5]; - var g = H[6]; - var h = H[7]; - - // Computation - for (var i = 0; i < 64; i++) { - if (i < 16) { - W[i] = M[offset + i] | 0; - } else { - var gamma0x = W[i - 15]; - var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ - ((gamma0x << 14) | (gamma0x >>> 18)) ^ - (gamma0x >>> 3); - - var gamma1x = W[i - 2]; - var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ - ((gamma1x << 13) | (gamma1x >>> 19)) ^ - (gamma1x >>> 10); - - W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; - } - - var ch = (e & f) ^ (~e & g); - var maj = (a & b) ^ (a & c) ^ (b & c); - - var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); - var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); - - var t1 = h + sigma1 + ch + K[i] + W[i]; - var t2 = sigma0 + maj; - - h = g; - g = f; - f = e; - e = (d + t1) | 0; - d = c; - c = b; - b = a; - a = (t1 + t2) | 0; - } - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - H[4] = (H[4] + e) | 0; - H[5] = (H[5] + f) | 0; - H[6] = (H[6] + g) | 0; - H[7] = (H[7] + h) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; - data.sigBytes = dataWords.length * 4; - - // Hash final blocks - this._process(); - - // Return final computed hash - return this._hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - } - }); - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.SHA256('message'); - * var hash = CryptoJS.SHA256(wordArray); - */ - C.SHA256 = Hasher._createHelper(SHA256); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacSHA256(message, key); - */ - C.HmacSHA256 = Hasher._createHmacHelper(SHA256); -}(Math)); - -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function (undefined) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var Base = C_lib.Base; - var X32WordArray = C_lib.WordArray; - - /** - * x64 namespace. - */ - var C_x64 = C.x64 = {}; - - /** - * A 64-bit word. - */ - var X64Word = C_x64.Word = Base.extend({ - /** - * Initializes a newly created 64-bit word. - * - * @param {number} high The high 32 bits. - * @param {number} low The low 32 bits. - * - * @example - * - * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); - */ - init: function (high, low) { - this.high = high; - this.low = low; - } - - /** - * Bitwise NOTs this word. - * - * @return {X64Word} A new x64-Word object after negating. - * - * @example - * - * var negated = x64Word.not(); - */ - // not: function () { - // var high = ~this.high; - // var low = ~this.low; - - // return X64Word.create(high, low); - // }, - - /** - * Bitwise ANDs this word with the passed word. - * - * @param {X64Word} word The x64-Word to AND with this word. - * - * @return {X64Word} A new x64-Word object after ANDing. - * - * @example - * - * var anded = x64Word.and(anotherX64Word); - */ - // and: function (word) { - // var high = this.high & word.high; - // var low = this.low & word.low; - - // return X64Word.create(high, low); - // }, - - /** - * Bitwise ORs this word with the passed word. - * - * @param {X64Word} word The x64-Word to OR with this word. - * - * @return {X64Word} A new x64-Word object after ORing. - * - * @example - * - * var ored = x64Word.or(anotherX64Word); - */ - // or: function (word) { - // var high = this.high | word.high; - // var low = this.low | word.low; - - // return X64Word.create(high, low); - // }, - - /** - * Bitwise XORs this word with the passed word. - * - * @param {X64Word} word The x64-Word to XOR with this word. - * - * @return {X64Word} A new x64-Word object after XORing. - * - * @example - * - * var xored = x64Word.xor(anotherX64Word); - */ - // xor: function (word) { - // var high = this.high ^ word.high; - // var low = this.low ^ word.low; - - // return X64Word.create(high, low); - // }, - - /** - * Shifts this word n bits to the left. - * - * @param {number} n The number of bits to shift. - * - * @return {X64Word} A new x64-Word object after shifting. - * - * @example - * - * var shifted = x64Word.shiftL(25); - */ - // shiftL: function (n) { - // if (n < 32) { - // var high = (this.high << n) | (this.low >>> (32 - n)); - // var low = this.low << n; - // } else { - // var high = this.low << (n - 32); - // var low = 0; - // } - - // return X64Word.create(high, low); - // }, - - /** - * Shifts this word n bits to the right. - * - * @param {number} n The number of bits to shift. - * - * @return {X64Word} A new x64-Word object after shifting. - * - * @example - * - * var shifted = x64Word.shiftR(7); - */ - // shiftR: function (n) { - // if (n < 32) { - // var low = (this.low >>> n) | (this.high << (32 - n)); - // var high = this.high >>> n; - // } else { - // var low = this.high >>> (n - 32); - // var high = 0; - // } - - // return X64Word.create(high, low); - // }, - - /** - * Rotates this word n bits to the left. - * - * @param {number} n The number of bits to rotate. - * - * @return {X64Word} A new x64-Word object after rotating. - * - * @example - * - * var rotated = x64Word.rotL(25); - */ - // rotL: function (n) { - // return this.shiftL(n).or(this.shiftR(64 - n)); - // }, - - /** - * Rotates this word n bits to the right. - * - * @param {number} n The number of bits to rotate. - * - * @return {X64Word} A new x64-Word object after rotating. - * - * @example - * - * var rotated = x64Word.rotR(7); - */ - // rotR: function (n) { - // return this.shiftR(n).or(this.shiftL(64 - n)); - // }, - - /** - * Adds this word with the passed word. - * - * @param {X64Word} word The x64-Word to add with this word. - * - * @return {X64Word} A new x64-Word object after adding. - * - * @example - * - * var added = x64Word.add(anotherX64Word); - */ - // add: function (word) { - // var low = (this.low + word.low) | 0; - // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; - // var high = (this.high + word.high + carry) | 0; - - // return X64Word.create(high, low); - // } - }); - - /** - * An array of 64-bit words. - * - * @property {Array} words The array of CryptoJS.x64.Word objects. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var X64WordArray = C_x64.WordArray = Base.extend({ - /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example - * - * var wordArray = CryptoJS.x64.WordArray.create(); - * - * var wordArray = CryptoJS.x64.WordArray.create([ - * CryptoJS.x64.Word.create(0x00010203, 0x04050607), - * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) - * ]); - * - * var wordArray = CryptoJS.x64.WordArray.create([ - * CryptoJS.x64.Word.create(0x00010203, 0x04050607), - * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) - * ], 10); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 8; - } - }, - - /** - * Converts this 64-bit word array to a 32-bit word array. - * - * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. - * - * @example - * - * var x32WordArray = x64WordArray.toX32(); - */ - toX32: function () { - // Shortcuts - var x64Words = this.words; - var x64WordsLength = x64Words.length; - - // Convert - var x32Words = []; - for (var i = 0; i < x64WordsLength; i++) { - var x64Word = x64Words[i]; - x32Words.push(x64Word.high); - x32Words.push(x64Word.low); - } - - return X32WordArray.create(x32Words, this.sigBytes); - }, - - /** - * Creates a copy of this word array. - * - * @return {X64WordArray} The clone. - * - * @example - * - * var clone = x64WordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - - // Clone "words" array - var words = clone.words = this.words.slice(0); - - // Clone each X64Word object - var wordsLength = words.length; - for (var i = 0; i < wordsLength; i++) { - words[i] = words[i].clone(); - } - - return clone; - } - }); -}()); -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var Hasher = C_lib.Hasher; - var C_x64 = C.x64; - var X64Word = C_x64.Word; - var X64WordArray = C_x64.WordArray; - var C_algo = C.algo; - - function X64Word_create() { - return X64Word.create.apply(X64Word, arguments); - } - - // Constants - var K = [ - X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), - X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), - X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), - X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), - X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), - X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), - X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), - X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), - X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), - X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), - X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), - X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), - X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), - X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), - X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), - X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), - X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), - X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), - X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), - X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), - X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), - X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), - X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), - X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), - X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), - X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), - X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), - X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), - X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), - X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), - X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), - X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), - X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), - X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), - X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), - X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), - X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), - X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), - X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), - X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) - ]; - - // Reusable objects - var W = []; - (function () { - for (var i = 0; i < 80; i++) { - W[i] = X64Word_create(); - } - }()); - - /** - * SHA-512 hash algorithm. - */ - var SHA512 = C_algo.SHA512 = Hasher.extend({ - _doReset: function () { - this._hash = new X64WordArray.init([ - new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), - new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), - new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), - new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) - ]); - }, - - _doProcessBlock: function (M, offset) { - // Shortcuts - var H = this._hash.words; - - var H0 = H[0]; - var H1 = H[1]; - var H2 = H[2]; - var H3 = H[3]; - var H4 = H[4]; - var H5 = H[5]; - var H6 = H[6]; - var H7 = H[7]; - - var H0h = H0.high; - var H0l = H0.low; - var H1h = H1.high; - var H1l = H1.low; - var H2h = H2.high; - var H2l = H2.low; - var H3h = H3.high; - var H3l = H3.low; - var H4h = H4.high; - var H4l = H4.low; - var H5h = H5.high; - var H5l = H5.low; - var H6h = H6.high; - var H6l = H6.low; - var H7h = H7.high; - var H7l = H7.low; - - // Working variables - var ah = H0h; - var al = H0l; - var bh = H1h; - var bl = H1l; - var ch = H2h; - var cl = H2l; - var dh = H3h; - var dl = H3l; - var eh = H4h; - var el = H4l; - var fh = H5h; - var fl = H5l; - var gh = H6h; - var gl = H6l; - var hh = H7h; - var hl = H7l; - - // Rounds - for (var i = 0; i < 80; i++) { - // Shortcut - var Wi = W[i]; - - // Extend message - if (i < 16) { - var Wih = Wi.high = M[offset + i * 2] | 0; - var Wil = Wi.low = M[offset + i * 2 + 1] | 0; - } else { - // Gamma0 - var gamma0x = W[i - 15]; - var gamma0xh = gamma0x.high; - var gamma0xl = gamma0x.low; - var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); - var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); - - // Gamma1 - var gamma1x = W[i - 2]; - var gamma1xh = gamma1x.high; - var gamma1xl = gamma1x.low; - var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); - var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7 = W[i - 7]; - var Wi7h = Wi7.high; - var Wi7l = Wi7.low; - - var Wi16 = W[i - 16]; - var Wi16h = Wi16.high; - var Wi16l = Wi16.low; - - var Wil = gamma0l + Wi7l; - var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); - var Wil = Wil + gamma1l; - var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); - var Wil = Wil + Wi16l; - var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); - - Wi.high = Wih; - Wi.low = Wil; - } - - var chh = (eh & fh) ^ (~eh & gh); - var chl = (el & fl) ^ (~el & gl); - var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); - var majl = (al & bl) ^ (al & cl) ^ (bl & cl); - - var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); - var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); - var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); - var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); - - // t1 = h + sigma1 + ch + K[i] + W[i] - var Ki = K[i]; - var Kih = Ki.high; - var Kil = Ki.low; - - var t1l = hl + sigma1l; - var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); - var t1l = t1l + chl; - var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); - var t1l = t1l + Kil; - var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); - var t1l = t1l + Wil; - var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); - - // t2 = sigma0 + maj - var t2l = sigma0l + majl; - var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); - - // Update working variables - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - el = (dl + t1l) | 0; - eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - al = (t1l + t2l) | 0; - ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; - } - - // Intermediate hash value - H0l = H0.low = (H0l + al); - H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); - H1l = H1.low = (H1l + bl); - H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); - H2l = H2.low = (H2l + cl); - H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); - H3l = H3.low = (H3l + dl); - H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); - H4l = H4.low = (H4l + el); - H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); - H5l = H5.low = (H5l + fl); - H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); - H6l = H6.low = (H6l + gl); - H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); - H7l = H7.low = (H7l + hl); - H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; - - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); - dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; - data.sigBytes = dataWords.length * 4; - - // Hash final blocks - this._process(); - - // Convert hash to 32-bit word array before returning - var hash = this._hash.toX32(); - - // Return final computed hash - return hash; - }, - - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); - - return clone; - }, - - blockSize: 1024/32 - }); - - /** - * Shortcut function to the hasher's object interface. - * - * @param {WordArray|string} message The message to hash. - * - * @return {WordArray} The hash. - * - * @static - * - * @example - * - * var hash = CryptoJS.SHA512('message'); - * var hash = CryptoJS.SHA512(wordArray); - */ - C.SHA512 = Hasher._createHelper(SHA512); - - /** - * Shortcut function to the HMAC's object interface. - * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. - * - * @return {WordArray} The HMAC. - * - * @static - * - * @example - * - * var hmac = CryptoJS.HmacSHA512(message, key); - */ - C.HmacSHA512 = Hasher._createHmacHelper(SHA512); -}()); - diff --git a/lib/defaultHttpRequest.js b/lib/defaultHttpRequest.js deleted file mode 100644 index c62cf235..00000000 --- a/lib/defaultHttpRequest.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @constructor - */ -function DefaultHttpRequest() { - - /** - * @name _promiseFactory - * @type DefaultPromiseFactory - */ - - /** - * @param {XMLHttpRequest} xhr - * @param {object.} headers - */ - function setHeaders(xhr, headers) { - var keys = Object.keys(headers); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = headers[key]; - - xhr.setRequestHeader(key, value); - } - } - - /** - * @param {string} url - * @param {{ headers: object. }} [config] - * @returns {Promise} - */ - this.getJSON = function (url, config) { - return _promiseFactory.create(function (resolve, reject) { - - try { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url); - xhr.responseType = "json"; - - if (config) { - if (config.headers) { - setHeaders(xhr, config.headers); - } - } - - xhr.onload = function () { - try { - if (xhr.status === 200) { - var response = ""; - // To support IE9 get the response from xhr.responseText not xhr.response - if (window.XDomainRequest) { - response = xhr.responseText; - } else { - response = xhr.response; - } - if (typeof response === "string") { - response = JSON.parse(response); - } - resolve(response); - } - else { - reject(Error(xhr.statusText + "(" + xhr.status + ")")); - } - } - catch (err) { - reject(err); - } - }; - - xhr.onerror = function () { - reject(Error("Network error")); - }; - - xhr.send(); - } - catch (err) { - return reject(err); - } - }); - }; -} - -_httpRequest = new DefaultHttpRequest(); diff --git a/lib/defaultPromiseFactory.js b/lib/defaultPromiseFactory.js deleted file mode 100644 index 91e3fa67..00000000 --- a/lib/defaultPromiseFactory.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @constructor - * @param {Promise} promise - */ -function DefaultPromise(promise) { - - /** - * @param {function(*):*} successCallback - * @param {function(*):*} errorCallback - * @returns {DefaultPromise} - */ - this.then = function (successCallback, errorCallback) { - var childPromise = promise.then(successCallback, errorCallback); - - return new DefaultPromise(childPromise); - }; - - /** - * - * @param {function(*):*} errorCallback - * @returns {DefaultPromise} - */ - this.catch = function (errorCallback) { - var childPromise = promise.catch(errorCallback); - - return new DefaultPromise(childPromise); - }; -} - -/** - * @constructor - */ -function DefaultPromiseFactory() { - - this.resolve = function (value) { - return new DefaultPromise(Promise.resolve(value)); - }; - - this.reject = function (reason) { - return new DefaultPromise(Promise.reject(reason)); - }; - - /** - * @param {function(resolve:function, reject:function)} callback - * @returns {DefaultPromise} - */ - this.create = function (callback) { - return new DefaultPromise(new Promise(callback)); - }; -} - -_promiseFactory = new DefaultPromiseFactory(); \ No newline at end of file diff --git a/lib/es6-promise-3.0.2.js b/lib/es6-promise-3.0.2.js deleted file mode 100644 index 88144c91..00000000 --- a/lib/es6-promise-3.0.2.js +++ /dev/null @@ -1,967 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 3.0.2 - */ - -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - var lib$es6$promise$asap$$customSchedulerFn; - - var lib$es6$promise$asap$$asap = function asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (lib$es6$promise$asap$$customSchedulerFn) { - lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); - } else { - lib$es6$promise$asap$$scheduleFlush(); - } - } - } - - function lib$es6$promise$asap$$setScheduler(scheduleFn) { - lib$es6$promise$asap$$customSchedulerFn = scheduleFn; - } - - function lib$es6$promise$asap$$setAsap(asapFn) { - lib$es6$promise$asap$$asap = asapFn; - } - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$asap(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; - lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; - lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$asap(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - diff --git a/lib/iife-end.js b/lib/iife-end.js deleted file mode 100644 index e4920812..00000000 --- a/lib/iife-end.js +++ /dev/null @@ -1,5 +0,0 @@ - // exports - OidcClient._promiseFactory = _promiseFactory; - OidcClient._httpRequest = _httpRequest; - window.OidcClient = OidcClient; -})(); \ No newline at end of file diff --git a/lib/iife-start.js b/lib/iife-start.js deleted file mode 100644 index 24760f04..00000000 --- a/lib/iife-start.js +++ /dev/null @@ -1,5 +0,0 @@ -(function () { - - // globals - var _promiseFactory; - var _httpRequest; \ No newline at end of file diff --git a/lib/json-sans-eval.js b/lib/json-sans-eval.js deleted file mode 100644 index da0248e5..00000000 --- a/lib/json-sans-eval.js +++ /dev/null @@ -1,240 +0,0 @@ -/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval - */ -// This source code is free for use in the public domain. -// NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - -// http://code.google.com/p/json-sans-eval/ - -/** - * Parses a string of well-formed JSON text. - * - * If the input is not well-formed, then behavior is undefined, but it is - * deterministic and is guaranteed not to modify any object other than its - * return value. - * - * This does not use `eval` so is less likely to have obscure security bugs than - * json2.js. - * It is optimized for speed, so is much faster than json_parse.js. - * - * This library should be used whenever security is a concern (when JSON may - * come from an untrusted source), speed is a concern, and erroring on malformed - * JSON is *not* a concern. - * - * Pros Cons - * +-----------------------+-----------------------+ - * json_sans_eval.js | Fast, secure | Not validating | - * +-----------------------+-----------------------+ - * json_parse.js | Validating, secure | Slow | - * +-----------------------+-----------------------+ - * json2.js | Fast, some validation | Potentially insecure | - * +-----------------------+-----------------------+ - * - * json2.js is very fast, but potentially insecure since it calls `eval` to - * parse JSON data, so an attacker might be able to supply strange JS that - * looks like JSON, but that executes arbitrary javascript. - * If you do have to use json2.js with untrusted data, make sure you keep - * your version of json2.js up to date so that you get patches as they're - * released. - * - * @param {string} json per RFC 4627 - * @param {function (this:Object, string, *):*} opt_reviver optional function - * that reworks JSON objects post-parse per Chapter 15.12 of EcmaScript3.1. - * If supplied, the function is called with a string key, and a value. - * The value is the property of 'this'. The reviver should return - * the value to use in its place. So if dates were serialized as - * {@code { "type": "Date", "time": 1234 }}, then a reviver might look like - * {@code - * function (key, value) { - * if (value && typeof value === 'object' && 'Date' === value.type) { - * return new Date(value.time); - * } else { - * return value; - * } - * }}. - * If the reviver returns {@code undefined} then the property named by key - * will be deleted from its container. - * {@code this} is bound to the object containing the specified property. - * @return {Object|Array} - * @author Mike Samuel - */ -var jsonParse = (function () { - var number - = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)'; - var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]' - + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))'; - var string = '(?:\"' + oneChar + '*\")'; - - // Will match a value in a well-formed JSON file. - // If the input is not well-formed, may match strangely, but not in an unsafe - // way. - // Since this only matches value tokens, it does not match whitespace, colons, - // or commas. - var jsonToken = new RegExp( - '(?:false|true|null|[\\{\\}\\[\\]]' - + '|' + number - + '|' + string - + ')', 'g'); - - // Matches escape sequences in a string literal - var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g'); - - // Decodes escape sequences in object literals - var escapes = { - '"': '"', - '/': '/', - '\\': '\\', - 'b': '\b', - 'f': '\f', - 'n': '\n', - 'r': '\r', - 't': '\t' - }; - function unescapeOne(_, ch, hex) { - return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16)); - } - - // A non-falsy value that coerces to the empty string when used as a key. - var EMPTY_STRING = new String(''); - var SLASH = '\\'; - - // Constructor to use based on an open token. - var firstTokenCtors = { '{': Object, '[': Array }; - - var hop = Object.hasOwnProperty; - - return function (json, opt_reviver) { - // Split into tokens - var toks = json.match(jsonToken); - // Construct the object to return - var result; - var tok = toks[0]; - var topLevelPrimitive = false; - if ('{' === tok) { - result = {}; - } else if ('[' === tok) { - result = []; - } else { - // The RFC only allows arrays or objects at the top level, but the JSON.parse - // defined by the EcmaScript 5 draft does allow strings, booleans, numbers, and null - // at the top level. - result = []; - topLevelPrimitive = true; - } - - // If undefined, the key in an object key/value record to use for the next - // value parsed. - var key; - // Loop over remaining tokens maintaining a stack of uncompleted objects and - // arrays. - var stack = [result]; - for (var i = 1 - topLevelPrimitive, n = toks.length; i < n; ++i) { - tok = toks[i]; - - var cont; - switch (tok.charCodeAt(0)) { - default: // sign or digit - cont = stack[0]; - cont[key || cont.length] = +(tok); - key = void 0; - break; - case 0x22: // '"' - tok = tok.substring(1, tok.length - 1); - if (tok.indexOf(SLASH) !== -1) { - tok = tok.replace(escapeSequence, unescapeOne); - } - cont = stack[0]; - if (!key) { - if (cont instanceof Array) { - key = cont.length; - } else { - key = tok || EMPTY_STRING; // Use as key for next value seen. - break; - } - } - cont[key] = tok; - key = void 0; - break; - case 0x5b: // '[' - cont = stack[0]; - stack.unshift(cont[key || cont.length] = []); - key = void 0; - break; - case 0x5d: // ']' - stack.shift(); - break; - case 0x66: // 'f' - cont = stack[0]; - cont[key || cont.length] = false; - key = void 0; - break; - case 0x6e: // 'n' - cont = stack[0]; - cont[key || cont.length] = null; - key = void 0; - break; - case 0x74: // 't' - cont = stack[0]; - cont[key || cont.length] = true; - key = void 0; - break; - case 0x7b: // '{' - cont = stack[0]; - stack.unshift(cont[key || cont.length] = {}); - key = void 0; - break; - case 0x7d: // '}' - stack.shift(); - break; - } - } - // Fail if we've got an uncompleted object. - if (topLevelPrimitive) { - if (stack.length !== 1) { throw new Error(); } - result = result[0]; - } else { - if (stack.length) { throw new Error(); } - } - - if (opt_reviver) { - // Based on walk as implemented in http://www.json.org/json2.js - var walk = function (holder, key) { - var value = holder[key]; - if (value && typeof value === 'object') { - var toDelete = null; - for (var k in value) { - if (hop.call(value, k) && value !== holder) { - // Recurse to properties first. This has the effect of causing - // the reviver to be called on the object graph depth-first. - - // Since 'this' is bound to the holder of the property, the - // reviver can access sibling properties of k including ones - // that have not yet been revived. - - // The value returned by the reviver is used in place of the - // current value of property k. - // If it returns undefined then the property is deleted. - var v = walk(value, k); - if (v !== void 0) { - value[k] = v; - } else { - // Deleting properties inside the loop has vaguely defined - // semantics in ES3 and ES3.1. - if (!toDelete) { toDelete = []; } - toDelete.push(k); - } - } - } - if (toDelete) { - for (var i = toDelete.length; --i >= 0;) { - delete value[toDelete[i]]; - } - } - } - return opt_reviver.call(holder, key, value); - }; - result = walk({ '': result }, ''); - } - - return result; - }; -})(); diff --git a/lib/jws-3.0.js b/lib/jws-3.0.js deleted file mode 100644 index 228d5b7d..00000000 --- a/lib/jws-3.0.js +++ /dev/null @@ -1,705 +0,0 @@ -/*! jws-3.0.2 (c) 2013 Kenji Urushima | kjur.github.com/jsjws/license - */ -/* - * jws.js - JSON Web Signature Class - * - * version: 3.0.2 (2013 Sep 24) - * - * Copyright (c) 2010-2013 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsjws/license/ - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - */ - -/** - * @fileOverview - * @name jws-3.0.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version 3.0.1 (2013-Sep-24) - * @since jsjws 1.0 - * @license MIT License - */ - -if (typeof KJUR == "undefined" || !KJUR) KJUR = {}; -if (typeof KJUR.jws == "undefined" || !KJUR.jws) KJUR.jws = {}; - -/** - * JSON Web Signature(JWS) class.
- * @name KJUR.jws.JWS - * @class JSON Web Signature(JWS) class - * @property {Dictionary} parsedJWS This property is set after JWS signature verification.
- * Following "parsedJWS_*" properties can be accessed as "parsedJWS.*" because of - * JsDoc restriction. - * @property {String} parsedJWS_headB64U string of Encrypted JWS Header - * @property {String} parsedJWS_payloadB64U string of Encrypted JWS Payload - * @property {String} parsedJWS_sigvalB64U string of Encrypted JWS signature value - * @property {String} parsedJWS_si string of Signature Input - * @property {String} parsedJWS_sigvalH hexadecimal string of JWS signature value - * @property {String} parsedJWS_sigvalBI BigInteger(defined in jsbn.js) object of JWS signature value - * @property {String} parsedJWS_headS string of decoded JWS Header - * @property {String} parsedJWS_headS string of decoded JWS Payload - * @requires base64x.js, json-sans-eval.js and jsrsasign library - * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - * @see IETF I-D JSON Web Algorithms (JWA) - * @since jsjws 1.0 - * @description - *

Supported Algorithms

- * Here is supported algorithm names for {@link KJUR.jws.JWS.sign} and {@link KJUR.jws.JWS.verify} - * methods. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
alg valuespec requirementjsjws support
HS256REQUIREDSUPPORTED
HS384OPTIONALSUPPORTED
HS512OPTIONALSUPPORTED
RS256RECOMMENDEDSUPPORTED
RS384OPTIONALSUPPORTED
RS512OPTIONALSUPPORTED
ES256RECOMMENDED+SUPPORTED
ES384OPTIONALSUPPORTED
ES512OPTIONAL-
PS256OPTIONALSUPPORTED
PS384OPTIONALSUPPORTED
PS512OPTIONALSUPPORTED
noneREQUIREDSUPPORTED
- * NOTE: HS384 is supported since jsjws 3.0.2 with jsrsasign 4.1.4. - */ -KJUR.jws.JWS = function() { - - // === utility ============================================================= - - /** - * parse JWS string and set public property 'parsedJWS' dictionary.
- * @name parseJWS - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be parsed. - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @since jws 1.1 - */ - this.parseJWS = function(sJWS, sigValNotNeeded) { - if ((this.parsedJWS !== undefined) && - (sigValNotNeeded || (this.parsedJWS.sigvalH !== undefined))) { - return; - } - if (sJWS.match(/^([^.]+)\.([^.]+)\.([^.]+)$/) == null) { - throw "JWS signature is not a form of 'Head.Payload.SigValue'."; - } - var b6Head = RegExp.$1; - var b6Payload = RegExp.$2; - var b6SigVal = RegExp.$3; - var sSI = b6Head + "." + b6Payload; - this.parsedJWS = {}; - this.parsedJWS.headB64U = b6Head; - this.parsedJWS.payloadB64U = b6Payload; - this.parsedJWS.sigvalB64U = b6SigVal; - this.parsedJWS.si = sSI; - - if (!sigValNotNeeded) { - var hSigVal = b64utohex(b6SigVal); - var biSigVal = parseBigInt(hSigVal, 16); - this.parsedJWS.sigvalH = hSigVal; - this.parsedJWS.sigvalBI = biSigVal; - } - - var sHead = b64utoutf8(b6Head); - var sPayload = b64utoutf8(b6Payload); - this.parsedJWS.headS = sHead; - this.parsedJWS.payloadS = sPayload; - - if (!KJUR.jws.JWS.isSafeJSONString(sHead, this.parsedJWS, 'headP')) - throw "malformed JSON string for JWS Head: " + sHead; - }; - - // ==== JWS Validation ========================================================= - function _getSignatureInputByString(sHead, sPayload) { - return utf8tob64u(sHead) + "." + utf8tob64u(sPayload); - }; - - function _getHashBySignatureInput(sSignatureInput, sHashAlg) { - var hashfunc = function(s) { return KJUR.crypto.Util.hashString(s, sHashAlg); }; - if (hashfunc == null) throw "hash function not defined in jsrsasign: " + sHashAlg; - return hashfunc(sSignatureInput); - }; - - function _jws_verifySignature(sHead, sPayload, hSig, hN, hE) { - var sSignatureInput = _getSignatureInputByString(sHead, sPayload); - var biSig = parseBigInt(hSig, 16); - return _rsasign_verifySignatureWithArgs(sSignatureInput, biSig, hN, hE); - }; - - /** - * verify JWS signature with naked RSA public key.
- * This only supports "RS256" and "RS512" algorithm. - * @name verifyJWSByNE - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be verified - * @param {String} hN hexadecimal string for modulus of RSA public key - * @param {String} hE hexadecimal string for public exponent of RSA public key - * @return {String} returns 1 when JWS signature is valid, otherwise returns 0 - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.verify} - */ - this.verifyJWSByNE = function(sJWS, hN, hE) { - this.parseJWS(sJWS); - return _rsasign_verifySignatureWithArgs(this.parsedJWS.si, this.parsedJWS.sigvalBI, hN, hE); - }; - - /** - * verify JWS signature with RSA public key.
- * This only supports "RS256", "RS512", "PS256" and "PS512" algorithms. - * @name verifyJWSByKey - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be verified - * @param {RSAKey} key RSA public key - * @return {Boolean} returns true when JWS signature is valid, otherwise returns false - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.verify} - */ - this.verifyJWSByKey = function(sJWS, key) { - this.parseJWS(sJWS); - var hashAlg = _jws_getHashAlgFromParsedHead(this.parsedJWS.headP); - var isPSS = this.parsedJWS.headP['alg'].substr(0, 2) == "PS"; - - if (key.hashAndVerify) { - return key.hashAndVerify(hashAlg, - new Buffer(this.parsedJWS.si, 'utf8').toString('base64'), - b64utob64(this.parsedJWS.sigvalB64U), - 'base64', - isPSS); - } else if (isPSS) { - return key.verifyStringPSS(this.parsedJWS.si, - this.parsedJWS.sigvalH, hashAlg); - } else { - return key.verifyString(this.parsedJWS.si, - this.parsedJWS.sigvalH); - } - }; - - /** - * verify JWS signature by PEM formatted X.509 certificate.
- * This only supports "RS256" and "RS512" algorithm. - * @name verifyJWSByPemX509Cert - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sJWS JWS signature string to be verified - * @param {String} sPemX509Cert string of PEM formatted X.509 certificate - * @return {String} returns 1 when JWS signature is valid, otherwise returns 0 - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - * @throws if JWS Header is a malformed JSON string. - * @since 1.1 - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.verify} - */ - this.verifyJWSByPemX509Cert = function(sJWS, sPemX509Cert) { - this.parseJWS(sJWS); - var x509 = new X509(); - x509.readCertPEM(sPemX509Cert); - return x509.subjectPublicKeyRSA.verifyString(this.parsedJWS.si, this.parsedJWS.sigvalH); - }; - - // ==== JWS Generation ========================================================= - function _jws_getHashAlgFromParsedHead(head) { - var sigAlg = head["alg"]; - var hashAlg = ""; - - if (sigAlg != "RS256" && sigAlg != "RS512" && - sigAlg != "PS256" && sigAlg != "PS512") - throw "JWS signature algorithm not supported: " + sigAlg; - if (sigAlg.substr(2) == "256") hashAlg = "sha256"; - if (sigAlg.substr(2) == "512") hashAlg = "sha512"; - return hashAlg; - }; - - function _jws_getHashAlgFromHead(sHead) { - return _jws_getHashAlgFromParsedHead(jsonParse(sHead)); - }; - - function _jws_generateSignatureValueBySI_NED(sHead, sPayload, sSI, hN, hE, hD) { - var rsa = new RSAKey(); - rsa.setPrivate(hN, hE, hD); - - var hashAlg = _jws_getHashAlgFromHead(sHead); - var sigValue = rsa.signString(sSI, hashAlg); - return sigValue; - }; - - function _jws_generateSignatureValueBySI_Key(sHead, sPayload, sSI, key, head) { - var hashAlg = null; - if (typeof head == "undefined") { - hashAlg = _jws_getHashAlgFromHead(sHead); - } else { - hashAlg = _jws_getHashAlgFromParsedHead(head); - } - - var isPSS = head['alg'].substr(0, 2) == "PS"; - - if (key.hashAndSign) { - return b64tob64u(key.hashAndSign(hashAlg, sSI, 'binary', 'base64', isPSS)); - } else if (isPSS) { - return hextob64u(key.signStringPSS(sSI, hashAlg)); - } else { - return hextob64u(key.signString(sSI, hashAlg)); - } - }; - - function _jws_generateSignatureValueByNED(sHead, sPayload, hN, hE, hD) { - var sSI = _getSignatureInputByString(sHead, sPayload); - return _jws_generateSignatureValueBySI_NED(sHead, sPayload, sSI, hN, hE, hD); - }; - - /** - * generate JWS signature by Header, Payload and a naked RSA private key.
- * This only supports "RS256" and "RS512" algorithm. - * @name generateJWSByNED - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {String} hN hexadecimal string for modulus of RSA public key - * @param {String} hE hexadecimal string for public exponent of RSA public key - * @param {String} hD hexadecimal string for private exponent of RSA private key - * @return {String} JWS signature string - * @throws if sHead is a malformed JSON string. - * @throws if supported signature algorithm was not specified in JSON Header. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.sign} - */ - this.generateJWSByNED = function(sHead, sPayload, hN, hE, hD) { - if (!KJUR.jws.JWS.isSafeJSONString(sHead)) throw "JWS Head is not safe JSON string: " + sHead; - var sSI = _getSignatureInputByString(sHead, sPayload); - var hSigValue = _jws_generateSignatureValueBySI_NED(sHead, sPayload, sSI, hN, hE, hD); - var b64SigValue = hextob64u(hSigValue); - - this.parsedJWS = {}; - this.parsedJWS.headB64U = sSI.split(".")[0]; - this.parsedJWS.payloadB64U = sSI.split(".")[1]; - this.parsedJWS.sigvalB64U = b64SigValue; - - return sSI + "." + b64SigValue; - }; - - /** - * generate JWS signature by Header, Payload and a RSA private key.
- * This only supports "RS256", "RS512", "PS256" and "PS512" algorithms. - * @name generateJWSByKey - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {RSAKey} RSA private key - * @return {String} JWS signature string - * @throws if sHead is a malformed JSON string. - * @throws if supported signature algorithm was not specified in JSON Header. - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.sign} - */ - this.generateJWSByKey = function(sHead, sPayload, key) { - var obj = {}; - if (!KJUR.jws.JWS.isSafeJSONString(sHead, obj, 'headP')) - throw "JWS Head is not safe JSON string: " + sHead; - var sSI = _getSignatureInputByString(sHead, sPayload); - var b64SigValue = _jws_generateSignatureValueBySI_Key(sHead, sPayload, sSI, key, obj.headP); - - this.parsedJWS = {}; - this.parsedJWS.headB64U = sSI.split(".")[0]; - this.parsedJWS.payloadB64U = sSI.split(".")[1]; - this.parsedJWS.sigvalB64U = b64SigValue; - - return sSI + "." + b64SigValue; - }; - - // === sign with PKCS#1 RSA private key ===================================================== - function _jws_generateSignatureValueBySI_PemPrvKey(sHead, sPayload, sSI, sPemPrvKey) { - var rsa = new RSAKey(); - rsa.readPrivateKeyFromPEMString(sPemPrvKey); - var hashAlg = _jws_getHashAlgFromHead(sHead); - var sigValue = rsa.signString(sSI, hashAlg); - return sigValue; - }; - - /** - * generate JWS signature by Header, Payload and a PEM formatted PKCS#1 RSA private key.
- * This only supports "RS256" and "RS512" algorithm. - * @name generateJWSByP1PrvKey - * @memberOf KJUR.jws.JWS - * @function - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {String} string for sPemPrvKey PEM formatted PKCS#1 RSA private key
- * Heading and trailing space characters in PEM key will be ignored. - * @return {String} JWS signature string - * @throws if sHead is a malformed JSON string. - * @throws if supported signature algorithm was not specified in JSON Header. - * @since 1.1 - * @deprecated from 3.0.0 please move to {@link KJUR.jws.JWS.sign} - */ - this.generateJWSByP1PrvKey = function(sHead, sPayload, sPemPrvKey) { - if (!KJUR.jws.JWS.isSafeJSONString(sHead)) throw "JWS Head is not safe JSON string: " + sHead; - var sSI = _getSignatureInputByString(sHead, sPayload); - var hSigValue = _jws_generateSignatureValueBySI_PemPrvKey(sHead, sPayload, sSI, sPemPrvKey); - var b64SigValue = hextob64u(hSigValue); - - this.parsedJWS = {}; - this.parsedJWS.headB64U = sSI.split(".")[0]; - this.parsedJWS.payloadB64U = sSI.split(".")[1]; - this.parsedJWS.sigvalB64U = b64SigValue; - - return sSI + "." + b64SigValue; - }; -}; - -// === major static method ======================================================== - -/** - * generate JWS signature by specified key
- * @name sign - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} alg JWS algorithm name to sign and force set to sHead or null - * @param {String} sHead string of JWS Header - * @param {String} sPayload string of JWS Payload - * @param {String} key string of private key or key object to sign - * @param {String} pass (OPTION)passcode to use encrypted private key - * @return {String} JWS signature string - * @since jws 3.0.0 - * @see jsrsasign KJUR.crypto.Signature method - * @see jsrsasign KJUR.crypto.Mac method - * @description - * This method supports following algorithms. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
alg valuespec requirementjsjws support
HS256REQUIREDSUPPORTED
HS384OPTIONAL-
HS512OPTIONALSUPPORTED
RS256RECOMMENDEDSUPPORTED
RS384OPTIONALSUPPORTED
RS512OPTIONALSUPPORTED
ES256RECOMMENDED+SUPPORTED
ES384OPTIONALSUPPORTED
ES512OPTIONAL-
PS256OPTIONALSUPPORTED
PS384OPTIONALSUPPORTED
PS512OPTIONALSUPPORTED
noneREQUIREDSUPPORTED
- *
- *
NOTE1: - *
salt length of RSAPSS signature is the same as the hash algorithm length - * because of IETF JOSE ML discussion. - *
NOTE2: - *
The reason of HS384 unsupport is - * CryptoJS HmacSHA384 bug. - *
- */ -KJUR.jws.JWS.sign = function(alg, sHeader, sPayload, key, pass) { - var ns1 = KJUR.jws.JWS; - - if (! ns1.isSafeJSONString(sHeader)) - throw "JWS Head is not safe JSON string: " + sHead; - - var pHeader = ns1.readSafeJSONString(sHeader); - - // 1. use alg if defined in sHeader - if ((alg == '' || alg == null) && - pHeader['alg'] !== undefined) { - alg = pHeader['alg']; - } - - // 2. set alg in sHeader if undefined - if ((alg != '' && alg != null) && - pHeader['alg'] === undefined) { - pHeader['alg'] = alg; - sHeader = JSON.stringify(pHeader); - } - - // 3. set signature algorithm like SHA1withRSA - var sigAlg = null; - if (ns1.jwsalg2sigalg[alg] === undefined) { - throw "unsupported alg name: " + alg; - } else { - sigAlg = ns1.jwsalg2sigalg[alg]; - } - - var uHeader = utf8tob64u(sHeader); - var uPayload = utf8tob64u(sPayload); - var uSignatureInput = uHeader + "." + uPayload - - // 4. sign - var hSig = ""; - if (sigAlg.substr(0, 4) == "Hmac") { - if (key === undefined) - throw "hexadecimal key shall be specified for HMAC"; - var mac = new KJUR.crypto.Mac({'alg': sigAlg, 'pass': hextorstr(key)}); - mac.updateString(uSignatureInput); - hSig = mac.doFinal(); - } else if (sigAlg.indexOf("withECDSA") != -1) { - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key, pass); - sig.updateString(uSignatureInput); - hASN1Sig = sig.sign(); - hSig = KJUR.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig); - } else if (sigAlg != "none") { - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key, pass); - sig.updateString(uSignatureInput); - hSig = sig.sign(); - } - - var uSig = hextob64u(hSig); - return uSignatureInput + "." + uSig; -}; - -/** - * verify JWS signature by specified key or certificate
- * @name verify - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} sJWS string of JWS signature to verify - * @param {String} key string of public key, certificate or key object to verify - * @return {Boolean} true if the signature is valid otherwise false - * @since jws 3.0.0 - * @see jsrsasign KJUR.crypto.Signature method - * @see jsrsasign KJUR.crypto.Mac method - */ -KJUR.jws.JWS.verify = function(sJWS, key) { - var jws = KJUR.jws.JWS; - var a = sJWS.split("."); - var uHeader = a[0]; - var uPayload = a[1]; - var uSignatureInput = uHeader + "." + uPayload; - var hSig = b64utohex(a[2]); - - var pHeader = jws.readSafeJSONString(b64utoutf8(a[0])); - var alg = null; - if (pHeader.alg === undefined) { - throw "algorithm not specified in header"; - } else { - alg = pHeader.alg; - } - - var sigAlg = null; - if (jws.jwsalg2sigalg[pHeader.alg] === undefined) { - throw "unsupported alg name: " + alg; - } else { - sigAlg = jws.jwsalg2sigalg[alg]; - } - - // x. verify - if (sigAlg == "none") { - return true; - } else if (sigAlg.substr(0, 4) == "Hmac") { - if (key === undefined) - throw "hexadecimal key shall be specified for HMAC"; - var mac = new KJUR.crypto.Mac({'alg': sigAlg, 'pass': hextorstr(key)}); - mac.updateString(uSignatureInput); - hSig2 = mac.doFinal(); - return hSig == hSig2; - } else if (sigAlg.indexOf("withECDSA") != -1) { - var hASN1Sig = null; - try { - hASN1Sig = KJUR.crypto.ECDSA.concatSigToASN1Sig(hSig); - } catch (ex) { - return false; - } - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key) - sig.updateString(uSignatureInput); - return sig.verify(hASN1Sig); - } else { - var sig = new KJUR.crypto.Signature({'alg': sigAlg}); - sig.init(key) - sig.updateString(uSignatureInput); - return sig.verify(hSig); - } -}; - -/* - * @since jws 3.0.0 - */ -KJUR.jws.JWS.jwsalg2sigalg = { - "HS256": "HmacSHA256", - //"HS384": "HmacSHA384", // unsupported because of CryptoJS bug - "HS512": "HmacSHA512", - "RS256": "SHA256withRSA", - "RS384": "SHA384withRSA", - "RS512": "SHA512withRSA", - "ES256": "SHA256withECDSA", - "ES384": "SHA384withECDSA", - //"ES512": "SHA512withECDSA", // unsupported because of jsrsasign's bug - "PS256": "SHA256withRSAandMGF1", - "PS384": "SHA384withRSAandMGF1", - "PS512": "SHA512withRSAandMGF1", - "none": "none", -}; - -// === utility static method ====================================================== - -/** - * check whether a String "s" is a safe JSON string or not.
- * If a String "s" is a malformed JSON string or an other object type - * this returns 0, otherwise this returns 1. - * @name isSafeJSONString - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} s JSON string - * @return {Number} 1 or 0 - */ -KJUR.jws.JWS.isSafeJSONString = function(s, h, p) { - var o = null; - try { - o = jsonParse(s); - if (typeof o != "object") return 0; - if (o.constructor === Array) return 0; - if (h) h[p] = o; - return 1; - } catch (ex) { - return 0; - } -}; - -/** - * read a String "s" as JSON object if it is safe.
- * If a String "s" is a malformed JSON string or not JSON string, - * this returns null, otherwise returns JSON object. - * @name readSafeJSONString - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} s JSON string - * @return {Object} JSON object or null - * @since 1.1.1 - */ -KJUR.jws.JWS.readSafeJSONString = function(s) { - var o = null; - try { - o = jsonParse(s); - if (typeof o != "object") return null; - if (o.constructor === Array) return null; - return o; - } catch (ex) { - return null; - } -}; - -/** - * get Encoed Signature Value from JWS string.
- * @name getEncodedSignatureValueFromJWS - * @memberOf KJUR.jws.JWS - * @function - * @static - * @param {String} sJWS JWS signature string to be verified - * @return {String} string of Encoded Signature Value - * @throws if sJWS is not comma separated string such like "Header.Payload.Signature". - */ -KJUR.jws.JWS.getEncodedSignatureValueFromJWS = function(sJWS) { - if (sJWS.match(/^[^.]+\.[^.]+\.([^.]+)$/) == null) { - throw "JWS signature is not a form of 'Head.Payload.SigValue'."; - } - return RegExp.$1; -}; - -/** - * IntDate class for time representation for JSON Web Token(JWT) - * @class KJUR.jws.IntDate class - * @name KJUR.jws.IntDate - * @since jws 3.0.1 - * @description - * Utility class for IntDate which is integer representation of UNIX origin time - * used in JSON Web Token(JWT). - */ -KJUR.jws.IntDate = function() { -}; - -/** - * @name get - * @memberOf KJUR.jws.IntDate - * @function - * @static - * @param {String} s string of time representation - * @return {Integer} UNIX origin time in seconds for argument 's' - * @since jws 3.0.1 - * @throws "unsupported format: s" when malformed format - * @description - * This method will accept following representation of time. - *
    - *
  • now - current time
  • - *
  • now + 1hour - after 1 hour from now
  • - *
  • now + 1day - after 1 day from now
  • - *
  • now + 1month - after 30 days from now
  • - *
  • now + 1year - after 365 days from now
  • - *
  • YYYYmmDDHHMMSSZ - UTC time (ex. 20130828235959Z)
  • - *
  • number - UNIX origin time (seconds from 1970-01-01 00:00:00) (ex. 1377714748)
  • - *
- */ -KJUR.jws.IntDate.get = function(s) { - if (s == "now") { - return KJUR.jws.IntDate.getNow(); - } else if (s == "now + 1hour") { - return KJUR.jws.IntDate.getNow() + 60 * 60; - } else if (s == "now + 1day") { - return KJUR.jws.IntDate.getNow() + 60 * 60 * 24; - } else if (s == "now + 1month") { - return KJUR.jws.IntDate.getNow() + 60 * 60 * 24 * 30; - } else if (s == "now + 1year") { - return KJUR.jws.IntDate.getNow() + 60 * 60 * 24 * 365; - } else if (s.match(/Z$/)) { - return KJUR.jws.IntDate.getZulu(s); - } else if (s.match(/^[0-9]+$/)) { - return parseInt(s); - } - throw "unsupported format: " + s; -}; - -KJUR.jws.IntDate.getZulu = function(s) { - if (a = s.match(/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z/)) { - var year = parseInt(RegExp.$1); - var month = parseInt(RegExp.$2) - 1; - var day = parseInt(RegExp.$3); - var hour = parseInt(RegExp.$4); - var min = parseInt(RegExp.$5); - var sec = parseInt(RegExp.$6); - var d = new Date(Date.UTC(year, month, day, hour, min, sec)); - return ~~(d / 1000); - } - throw "unsupported format: " + s; -}; - -/* - * @since jws 3.0.1 - */ -KJUR.jws.IntDate.getNow = function() { - var d = ~~(new Date() / 1000); - return d; -}; - -/* - * @since jws 3.0.1 - */ -KJUR.jws.IntDate.intDate2UTCString = function(intDate) { - var d = new Date(intDate * 1000); - return d.toUTCString(); -}; - -/* - * @since jws 3.0.1 - */ -KJUR.jws.IntDate.intDate2Zulu = function(intDate) { - var d = new Date(intDate * 1000); - var year = ("0000" + d.getUTCFullYear()).slice(-4); - var mon = ("00" + (d.getUTCMonth() + 1)).slice(-2); - var day = ("00" + d.getUTCDate()).slice(-2); - var hour = ("00" + d.getUTCHours()).slice(-2); - var min = ("00" + d.getUTCMinutes()).slice(-2); - var sec = ("00" + d.getUTCSeconds()).slice(-2); - return year + mon + day + hour + min + sec + "Z"; -}; diff --git a/lib/rsa.js b/lib/rsa.js deleted file mode 100644 index 98b910d7..00000000 --- a/lib/rsa.js +++ /dev/null @@ -1,4075 +0,0 @@ -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var b64pad="="; - -function hex2b64(h) { - var i; - var c; - var ret = ""; - for(i = 0; i+3 <= h.length; i+=3) { - c = parseInt(h.substring(i,i+3),16); - ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); - } - if(i+1 == h.length) { - c = parseInt(h.substring(i,i+1),16); - ret += b64map.charAt(c << 2); - } - else if(i+2 == h.length) { - c = parseInt(h.substring(i,i+2),16); - ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); - } - if (b64pad) while((ret.length & 3) > 0) ret += b64pad; - return ret; -} - -// convert a base64 string to hex -function b64tohex(s) { - var ret = "" - var i; - var k = 0; // b64 state, 0-3 - var slop; - var v; - for(i = 0; i < s.length; ++i) { - if(s.charAt(i) == b64pad) break; - v = b64map.indexOf(s.charAt(i)); - if(v < 0) continue; - if(k == 0) { - ret += int2char(v >> 2); - slop = v & 3; - k = 1; - } - else if(k == 1) { - ret += int2char((slop << 2) | (v >> 4)); - slop = v & 0xf; - k = 2; - } - else if(k == 2) { - ret += int2char(slop); - ret += int2char(v >> 2); - slop = v & 3; - k = 3; - } - else { - ret += int2char((slop << 2) | (v >> 4)); - ret += int2char(v & 0xf); - k = 0; - } - } - if(k == 1) - ret += int2char(slop << 2); - return ret; -} - -// convert a base64 string to a byte/number array -function b64toBA(s) { - //piggyback on b64tohex for now, optimize later - var h = b64tohex(s); - var i; - var a = new Array(); - for(i = 0; 2*i < h.length; ++i) { - a[i] = parseInt(h.substring(2*i,2*i+2),16); - } - return a; -} -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Copyright (c) 2005 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. - -// Basic JavaScript BN library - subset useful for RSA encryption. - -// Bits per digit -var dbits; - -// JavaScript engine analysis -var canary = 0xdeadbeefcafe; -var j_lm = ((canary&0xffffff)==0xefcafe); - -// (public) Constructor -function BigInteger(a,b,c) { - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); -} - -// return new, unset BigInteger -function nbi() { return new BigInteger(null); } - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this[i++]+w[j]+c; - c = Math.floor(v/0x4000000); - w[j++] = v&0x3ffffff; - } - return c; -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i,x,w,j,c,n) { - var xl = x&0x7fff, xh = x>>15; - while(--n >= 0) { - var l = this[i]&0x7fff; - var h = this[i++]>>15; - var m = xh*l+h*xl; - l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); - c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); - w[j++] = l&0x3fffffff; - } - return c; -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i,x,w,j,c,n) { - var xl = x&0x3fff, xh = x>>14; - while(--n >= 0) { - var l = this[i]&0x3fff; - var h = this[i++]>>14; - var m = xh*l+h*xl; - l = xl*l+((m&0x3fff)<<14)+w[j]+c; - c = (l>>28)+(m>>14)+xh*h; - w[j++] = l&0xfffffff; - } - return c; -} -if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; -} -else if(j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; -} -else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; -} - -BigInteger.prototype.DB = dbits; -BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; -} - -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1; - this.s = (x<0)?-1:0; - if(x > 0) this[0] = x; - else if(x < -1) this[0] = x+this.DV; - else this.t = 0; -} - -// return bigint initialized to value -function nbv(i) { var r = nbi(); r.fromInt(i); return r; } - -// (protected) set from string and radix -function bnpFromString(s,b) { - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 256) k = 8; // byte array - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else { this.fromRadix(s,b); return; } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while(--i >= 0) { - var x = (k==8)?s[i]&0xff:intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if(sh == 0) - this[this.t++] = x; - else if(sh+k > this.DB) { - this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); - } - else - this[this.t-1] |= x<= this.DB) sh -= this.DB; - } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; -} - -// (public) return string representation in given radix -function bnToString(b) { - if(this.s < 0) return "-"+this.negate().toString(b); - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else return this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this[i]&((1<>(p+=this.DB-k); - } - else { - d = (this[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } - } - if(d > 0) m = true; - if(m) r += int2char(d); - } - } - return m?r:"0"; -} - -// (public) -this -function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - -// (public) |this| -function bnAbs() { return (this.s<0)?this.negate():this; } - -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s-a.s; - if(r != 0) return r; - var i = this.t; - r = i-a.t; - if(r != 0) return (this.s<0)?-r:r; - while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; - return 0; -} - -// returns bit length of the integer x -function nbits(x) { - var r = 1, t; - if((t=x>>>16) != 0) { x = t; r += 16; } - if((t=x>>8) != 0) { x = t; r += 8; } - if((t=x>>4) != 0) { x = t; r += 4; } - if((t=x>>2) != 0) { x = t; r += 2; } - if((t=x>>1) != 0) { x = t; r += 1; } - return r; -} - -// (public) return the number of bits in "this" -function bnBitLength() { - if(this.t <= 0) return 0; - return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); -} - -// (protected) r = this << n*DB -function bnpDLShiftTo(n,r) { - var i; - for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; - for(i = n-1; i >= 0; --i) r[i] = 0; - r.t = this.t+n; - r.s = this.s; -} - -// (protected) r = this >> n*DB -function bnpDRShiftTo(n,r) { - for(var i = n; i < this.t; ++i) r[i-n] = this[i]; - r.t = Math.max(this.t-n,0); - r.s = this.s; -} - -// (protected) r = this << n -function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r[i+ds+1] = (this[i]>>cbs)|c; - c = (this[i]&bm)<= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); -} - -// (protected) r = this >> n -function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r[i-ds-1] |= (this[i]&bm)<>bs; - } - if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c -= a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r[i++] = this.DV+c; - else if(c > 0) r[i++] = c; - r.t = i; - r.clamp(); -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a,r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i+y.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); - r.s = 0; - r.clamp(); - if(this.s != a.s) BigInteger.ZERO.subTo(r,r); -} - -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2*x.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < x.t-1; ++i) { - var c = x.am(i,x[i],r,2*i,0,1); - if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { - r[i+x.t] -= x.DV; - r[i+x.t+1] = 1; - } - } - if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); - r.s = 0; - r.clamp(); -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m,q,r) { - var pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus - if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } - else { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y[ys-1]; - if(y0 == 0) return; - var yt = y0*(1<1)?y[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 0) { - r[r.t++] = 1; - r.subTo(t,r); - } - BigInteger.ONE.dlShiftTo(ys,t); - t.subTo(y,y); // "negative" y so we can replace sub with am later - while(y.t < ys) y[y.t++] = 0; - while(--j >= 0) { - // Estimate quotient digit - var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); - if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out - y.dlShiftTo(j,t); - r.subTo(t,r); - while(r[i] < --qd) r.subTo(t,r); - } - } - if(q != null) { - r.drShiftTo(ys,q); - if(ts != ms) BigInteger.ZERO.subTo(q,q); - } - r.t = ys; - r.clamp(); - if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder - if(ts < 0) BigInteger.ZERO.subTo(r,r); -} - -// (public) this mod a -function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); - return r; -} - -// Modular reduction using "classic" algorithm -function Classic(m) { this.m = m; } -function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; -} -function cRevert(x) { return x; } -function cReduce(x) { x.divRemTo(this.m,null,x); } -function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } -function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -Classic.prototype.convert = cConvert; -Classic.prototype.revert = cRevert; -Classic.prototype.reduce = cReduce; -Classic.prototype.mulTo = cMulTo; -Classic.prototype.sqrTo = cSqrTo; - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if(this.t < 1) return 0; - var x = this[0]; - if((x&1) == 0) return 0; - var y = x&3; // y == 1/x mod 2^2 - y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 - y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 - y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y>0)?this.DV-y:-y; -} - -// Montgomery reduction -function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp&0x7fff; - this.mph = this.mp>>15; - this.um = (1<<(m.DB-15))-1; - this.mt2 = 2*m.t; -} - -// xR mod m -function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t,r); - r.divRemTo(this.m,null,r); - if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); - return r; -} - -// x/R mod m -function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; -} - -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while(x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for(var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i]&0x7fff; - var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; - // use am to combine the multiply-shift-add into one call - j = i+this.m.t; - x[j] += this.m.am(0,u0,x,i,0,this.m.t); - // propagate carry - while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } - } - x.clamp(); - x.drShiftTo(this.m.t,x); - if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} - -// r = "x^2/R mod m"; x != r -function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -// r = "xy/R mod m"; x,y != r -function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - -Montgomery.prototype.convert = montConvert; -Montgomery.prototype.revert = montRevert; -Montgomery.prototype.reduce = montReduce; -Montgomery.prototype.mulTo = montMulTo; -Montgomery.prototype.sqrTo = montSqrTo; - -// (protected) true iff this is even -function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e,z) { - if(e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); -} - -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e,m) { - var z; - if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); - return this.exp(e,z); -} - -// protected -BigInteger.prototype.copyTo = bnpCopyTo; -BigInteger.prototype.fromInt = bnpFromInt; -BigInteger.prototype.fromString = bnpFromString; -BigInteger.prototype.clamp = bnpClamp; -BigInteger.prototype.dlShiftTo = bnpDLShiftTo; -BigInteger.prototype.drShiftTo = bnpDRShiftTo; -BigInteger.prototype.lShiftTo = bnpLShiftTo; -BigInteger.prototype.rShiftTo = bnpRShiftTo; -BigInteger.prototype.subTo = bnpSubTo; -BigInteger.prototype.multiplyTo = bnpMultiplyTo; -BigInteger.prototype.squareTo = bnpSquareTo; -BigInteger.prototype.divRemTo = bnpDivRemTo; -BigInteger.prototype.invDigit = bnpInvDigit; -BigInteger.prototype.isEven = bnpIsEven; -BigInteger.prototype.exp = bnpExp; - -// public -BigInteger.prototype.toString = bnToString; -BigInteger.prototype.negate = bnNegate; -BigInteger.prototype.abs = bnAbs; -BigInteger.prototype.compareTo = bnCompareTo; -BigInteger.prototype.bitLength = bnBitLength; -BigInteger.prototype.mod = bnMod; -BigInteger.prototype.modPowInt = bnModPowInt; - -// "constants" -BigInteger.ZERO = nbv(0); -BigInteger.ONE = nbv(1); -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Copyright (c) 2005-2009 Tom Wu -// All Rights Reserved. -// See "LICENSE" for details. - -// Extended JavaScript BN functions, required for RSA private ops. - -// Version 1.1: new BigInteger("0", 10) returns "proper" zero -// Version 1.2: square() API, isProbablePrime fix - -// (public) -function bnClone() { var r = nbi(); this.copyTo(r); return r; } - -// (public) return value as integer -function bnIntValue() { - if(this.s < 0) { - if(this.t == 1) return this[0]-this.DV; - else if(this.t == 0) return -1; - } - else if(this.t == 1) return this[0]; - else if(this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1]&((1<<(32-this.DB))-1))<>24; } - -// (public) return value as short (assumes DB>=16) -function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } - -// (protected) return x s.t. r^x < DV -function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } - -// (public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { - if(this.s < 0) return -1; - else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; -} - -// (protected) convert to radix string -function bnpToRadix(b) { - if(b == null) b = 10; - if(this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b,cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d,y,z); - while(y.signum() > 0) { - r = (a+z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d,y,z); - } - return z.intValue().toString(b) + r; -} - -// (protected) convert from radix string -function bnpFromRadix(s,b) { - this.fromInt(0); - if(b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b,cs), mi = false, j = 0, w = 0; - for(var i = 0; i < s.length; ++i) { - var x = intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } - } - if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); - } - if(mi) BigInteger.ZERO.subTo(this,this); -} - -// (protected) alternate constructor -function bnpFromNumber(a,b,c) { - if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); - } - } - } - else { - // new BigInteger(int,RNG) - var x = new Array(), t = a&7; - x.length = (a>>3)+1; - b.nextBytes(x); - if(t > 0) x[0] &= ((1< 0) { - if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this[i]&((1<>(p+=this.DB-8); - } - else { - d = (this[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; - } - } - return r; -} - -function bnEquals(a) { return(this.compareTo(a)==0); } -function bnMin(a) { return(this.compareTo(a)<0)?this:a; } -function bnMax(a) { return(this.compareTo(a)>0)?this:a; } - -// (protected) r = this op a (bitwise) -function bnpBitwiseTo(a,op,r) { - var i, f, m = Math.min(a.t,this.t); - for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); - if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r[i] = op(this[i],f); - r.t = this.t; - } - else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); - r.t = a.t; - } - r.s = op(this.s,a.s); - r.clamp(); -} - -// (public) this & a -function op_and(x,y) { return x&y; } -function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } - -// (public) this | a -function op_or(x,y) { return x|y; } -function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } - -// (public) this ^ a -function op_xor(x,y) { return x^y; } -function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - -// (public) this & ~a -function op_andnot(x,y) { return x&~y; } -function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } - -// (public) ~this -function bnNot() { - var r = nbi(); - for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; -} - -// (public) this << n -function bnShiftLeft(n) { - var r = nbi(); - if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); - return r; -} - -// (public) this >> n -function bnShiftRight(n) { - var r = nbi(); - if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); - return r; -} - -// return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { - if(x == 0) return -1; - var r = 0; - if((x&0xffff) == 0) { x >>= 16; r += 16; } - if((x&0xff) == 0) { x >>= 8; r += 8; } - if((x&0xf) == 0) { x >>= 4; r += 4; } - if((x&3) == 0) { x >>= 2; r += 2; } - if((x&1) == 0) ++r; - return r; -} - -// (public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { - for(var i = 0; i < this.t; ++i) - if(this[i] != 0) return i*this.DB+lbit(this[i]); - if(this.s < 0) return this.t*this.DB; - return -1; -} - -// return number of 1 bits in x -function cbit(x) { - var r = 0; - while(x != 0) { x &= x-1; ++r; } - return r; -} - -// (public) return number of set bits -function bnBitCount() { - var r = 0, x = this.s&this.DM; - for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); - return r; -} - -// (public) true iff nth bit is set -function bnTestBit(n) { - var j = Math.floor(n/this.DB); - if(j >= this.t) return(this.s!=0); - return((this[j]&(1<<(n%this.DB)))!=0); -} - -// (protected) this op (1<>= this.DB; - } - if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c += a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = (c<0)?-1:0; - if(c > 0) r[i++] = c; - else if(c < -1) r[i++] = this.DV+c; - r.t = i; - r.clamp(); -} - -// (public) this + a -function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } - -// (public) this - a -function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - -// (public) this * a -function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } - -// (public) this^2 -function bnSquare() { var r = nbi(); this.squareTo(r); return r; } - -// (public) this / a -function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } - -// (public) this % a -function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } - -// (public) [this/a,this%a] -function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a,q,r); - return new Array(q,r); -} - -// (protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { - this[this.t] = this.am(0,n-1,this,0,0,this.t); - ++this.t; - this.clamp(); -} - -// (protected) this += n << w words, this >= 0 -function bnpDAddOffset(n,w) { - if(n == 0) return; - while(this.t <= w) this[this.t++] = 0; - this[w] += n; - while(this[w] >= this.DV) { - this[w] -= this.DV; - if(++w >= this.t) this[this.t++] = 0; - ++this[w]; - } -} - -// A "null" reducer -function NullExp() {} -function nNop(x) { return x; } -function nMulTo(x,y,r) { x.multiplyTo(y,r); } -function nSqrTo(x,r) { x.squareTo(r); } - -NullExp.prototype.convert = nNop; -NullExp.prototype.revert = nNop; -NullExp.prototype.mulTo = nMulTo; -NullExp.prototype.sqrTo = nSqrTo; - -// (public) this^e -function bnPow(e) { return this.exp(e,new NullExp()); } - -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a,n,r) { - var i = Math.min(this.t+a.t,n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while(i > 0) r[--i] = 0; - var j; - for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); - for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); - r.clamp(); -} - -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a,n,r) { - --n; - var i = r.t = this.t+a.t-n; - r.s = 0; // assumes a,this >= 0 - while(--i >= 0) r[i] = 0; - for(i = Math.max(n-this.t,0); i < a.t; ++i) - r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); - r.clamp(); - r.drShiftTo(1,r); -} - -// Barrett modular reduction -function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2*m.t,this.r2); - this.mu = this.r2.divide(m); - this.m = m; -} - -function barrettConvert(x) { - if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); - else if(x.compareTo(this.m) < 0) return x; - else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } -} - -function barrettRevert(x) { return x; } - -// x = x mod m (HAC 14.42) -function barrettReduce(x) { - x.drShiftTo(this.m.t-1,this.r2); - if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } - this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); - this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); - while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); - x.subTo(this.r2,x); - while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); -} - -// r = x^2 mod m; x != r -function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - -// r = x*y mod m; x,y != r -function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - -Barrett.prototype.convert = barrettConvert; -Barrett.prototype.revert = barrettRevert; -Barrett.prototype.reduce = barrettReduce; -Barrett.prototype.mulTo = barrettMulTo; -Barrett.prototype.sqrTo = barrettSqrTo; - -// (public) this^e % m (HAC 14.85) -function bnModPow(e,m) { - var i = e.bitLength(), k, r = nbv(1), z; - if(i <= 0) return r; - else if(i < 18) k = 1; - else if(i < 48) k = 3; - else if(i < 144) k = 4; - else if(i < 768) k = 5; - else k = 6; - if(i < 8) - z = new Classic(m); - else if(m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); - - // precomputation - var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; - } - } - - var j = e.t-1, w, is1 = true, r2 = nbi(), t; - i = nbits(e[j])-1; - while(j >= 0) { - if(i >= k1) w = (e[j]>>(i-k1))&km; - else { - w = (e[j]&((1<<(i+1))-1))<<(k1-i); - if(j > 0) w |= e[j-1]>>(this.DB+i-k1); - } - - n = k; - while((w&1) == 0) { w >>= 1; --n; } - if((i -= n) < 0) { i += this.DB; --j; } - if(is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; - } - else { - while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } - if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } - z.mulTo(r2,g[w],r); - } - - while(j >= 0 && (e[j]&(1< 0) { - x.rShiftTo(g,x); - y.rShiftTo(g,y); - } - while(x.signum() > 0) { - if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); - if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); - if(x.compareTo(y) >= 0) { - x.subTo(y,x); - x.rShiftTo(1,x); - } - else { - y.subTo(x,y); - y.rShiftTo(1,y); - } - } - if(g > 0) y.lShiftTo(g,y); - return y; -} - -// (protected) this % n, n < 2^26 -function bnpModInt(n) { - if(n <= 0) return 0; - var d = this.DV%n, r = (this.s<0)?n-1:0; - if(this.t > 0) - if(d == 0) r = this[0]%n; - else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; - return r; -} - -// (public) 1/this % m (HAC 14.61) -function bnModInverse(m) { - var ac = m.isEven(); - if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while(u.signum() != 0) { - while(u.isEven()) { - u.rShiftTo(1,u); - if(ac) { - if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } - a.rShiftTo(1,a); - } - else if(!b.isEven()) b.subTo(m,b); - b.rShiftTo(1,b); - } - while(v.isEven()) { - v.rShiftTo(1,v); - if(ac) { - if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } - c.rShiftTo(1,c); - } - else if(!d.isEven()) d.subTo(m,d); - d.rShiftTo(1,d); - } - if(u.compareTo(v) >= 0) { - u.subTo(v,u); - if(ac) a.subTo(c,a); - b.subTo(d,b); - } - else { - v.subTo(u,v); - if(ac) c.subTo(a,c); - d.subTo(b,d); - } - } - if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if(d.compareTo(m) >= 0) return d.subtract(m); - if(d.signum() < 0) d.addTo(m,d); else return d; - if(d.signum() < 0) return d.add(m); else return d; -} - -var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; -var lplim = (1<<26)/lowprimes[lowprimes.length-1]; - -// (public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { - var i, x = this.abs(); - if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { - for(i = 0; i < lowprimes.length; ++i) - if(x[0] == lowprimes[i]) return true; - return false; - } - if(x.isEven()) return false; - i = 1; - while(i < lowprimes.length) { - var m = lowprimes[i], j = i+1; - while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while(i < j) if(m%lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); -} - -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if(k <= 0) return false; - var r = n1.shiftRight(k); - t = (t+1)>>1; - if(t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for(var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); - var y = a.modPow(r,this); - if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while(j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2,this); - if(y.compareTo(BigInteger.ONE) == 0) return false; - } - if(y.compareTo(n1) != 0) return false; - } - } - return true; -} - -// protected -BigInteger.prototype.chunkSize = bnpChunkSize; -BigInteger.prototype.toRadix = bnpToRadix; -BigInteger.prototype.fromRadix = bnpFromRadix; -BigInteger.prototype.fromNumber = bnpFromNumber; -BigInteger.prototype.bitwiseTo = bnpBitwiseTo; -BigInteger.prototype.changeBit = bnpChangeBit; -BigInteger.prototype.addTo = bnpAddTo; -BigInteger.prototype.dMultiply = bnpDMultiply; -BigInteger.prototype.dAddOffset = bnpDAddOffset; -BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; -BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; -BigInteger.prototype.modInt = bnpModInt; -BigInteger.prototype.millerRabin = bnpMillerRabin; - -// public -BigInteger.prototype.clone = bnClone; -BigInteger.prototype.intValue = bnIntValue; -BigInteger.prototype.byteValue = bnByteValue; -BigInteger.prototype.shortValue = bnShortValue; -BigInteger.prototype.signum = bnSigNum; -BigInteger.prototype.toByteArray = bnToByteArray; -BigInteger.prototype.equals = bnEquals; -BigInteger.prototype.min = bnMin; -BigInteger.prototype.max = bnMax; -BigInteger.prototype.and = bnAnd; -BigInteger.prototype.or = bnOr; -BigInteger.prototype.xor = bnXor; -BigInteger.prototype.andNot = bnAndNot; -BigInteger.prototype.not = bnNot; -BigInteger.prototype.shiftLeft = bnShiftLeft; -BigInteger.prototype.shiftRight = bnShiftRight; -BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; -BigInteger.prototype.bitCount = bnBitCount; -BigInteger.prototype.testBit = bnTestBit; -BigInteger.prototype.setBit = bnSetBit; -BigInteger.prototype.clearBit = bnClearBit; -BigInteger.prototype.flipBit = bnFlipBit; -BigInteger.prototype.add = bnAdd; -BigInteger.prototype.subtract = bnSubtract; -BigInteger.prototype.multiply = bnMultiply; -BigInteger.prototype.divide = bnDivide; -BigInteger.prototype.remainder = bnRemainder; -BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; -BigInteger.prototype.modPow = bnModPow; -BigInteger.prototype.modInverse = bnModInverse; -BigInteger.prototype.pow = bnPow; -BigInteger.prototype.gcd = bnGCD; -BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - -// JSBN-specific extension -BigInteger.prototype.square = bnSquare; - -// BigInteger interfaces not implemented in jsbn: - -// BigInteger(int signum, byte[] magnitude) -// double doubleValue() -// float floatValue() -// int hashCode() -// long longValue() -// static BigInteger valueOf(long val) -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Depends on jsbn.js and rng.js - -// Version 1.1: support utf-8 encoding in pkcs1pad2 - -// convert a (hex) string to a bignum object -function parseBigInt(str,r) { - return new BigInteger(str,r); -} - -function linebrk(s,n) { - var ret = ""; - var i = 0; - while(i + n < s.length) { - ret += s.substring(i,i+n) + "\n"; - i += n; - } - return ret + s.substring(i,s.length); -} - -function byte2Hex(b) { - if(b < 0x10) - return "0" + b.toString(16); - else - return b.toString(16); -} - -// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint -function pkcs1pad2(s,n) { - if(n < s.length + 11) { // TODO: fix for utf-8 - alert("Message too long for RSA"); - return null; - } - var ba = new Array(); - var i = s.length - 1; - while(i >= 0 && n > 0) { - var c = s.charCodeAt(i--); - if(c < 128) { // encode using utf-8 - ba[--n] = c; - } - else if((c > 127) && (c < 2048)) { - ba[--n] = (c & 63) | 128; - ba[--n] = (c >> 6) | 192; - } - else { - ba[--n] = (c & 63) | 128; - ba[--n] = ((c >> 6) & 63) | 128; - ba[--n] = (c >> 12) | 224; - } - } - ba[--n] = 0; - var rng = new SecureRandom(); - var x = new Array(); - while(n > 2) { // random non-zero pad - x[0] = 0; - while(x[0] == 0) rng.nextBytes(x); - ba[--n] = x[0]; - } - ba[--n] = 2; - ba[--n] = 0; - return new BigInteger(ba); -} - -// PKCS#1 (OAEP) mask generation function -function oaep_mgf1_arr(seed, len, hash) -{ - var mask = '', i = 0; - - while (mask.length < len) - { - mask += hash(String.fromCharCode.apply(String, seed.concat([ - (i & 0xff000000) >> 24, - (i & 0x00ff0000) >> 16, - (i & 0x0000ff00) >> 8, - i & 0x000000ff]))); - i += 1; - } - - return mask; -} - -var SHA1_SIZE = 20; - -// PKCS#1 (OAEP) pad input string s to n bytes, and return a bigint -function oaep_pad(s, n, hash) -{ - if (s.length + 2 * SHA1_SIZE + 2 > n) - { - throw "Message too long for RSA"; - } - - var PS = '', i; - - for (i = 0; i < n - s.length - 2 * SHA1_SIZE - 2; i += 1) - { - PS += '\x00'; - } - - var DB = rstr_sha1('') + PS + '\x01' + s; - var seed = new Array(SHA1_SIZE); - new SecureRandom().nextBytes(seed); - - var dbMask = oaep_mgf1_arr(seed, DB.length, hash || rstr_sha1); - var maskedDB = []; - - for (i = 0; i < DB.length; i += 1) - { - maskedDB[i] = DB.charCodeAt(i) ^ dbMask.charCodeAt(i); - } - - var seedMask = oaep_mgf1_arr(maskedDB, seed.length, rstr_sha1); - var maskedSeed = [0]; - - for (i = 0; i < seed.length; i += 1) - { - maskedSeed[i + 1] = seed[i] ^ seedMask.charCodeAt(i); - } - - return new BigInteger(maskedSeed.concat(maskedDB)); -} - -// "empty" RSA key constructor -function RSAKey() { - this.n = null; - this.e = 0; - this.d = null; - this.p = null; - this.q = null; - this.dmp1 = null; - this.dmq1 = null; - this.coeff = null; -} - -// Set the public key fields N and e from hex strings -function RSASetPublic(N,E) { - this.isPublic = true; - if (typeof N !== "string") - { - this.n = N; - this.e = E; - } - else if(N != null && E != null && N.length > 0 && E.length > 0) { - this.n = parseBigInt(N,16); - this.e = parseInt(E,16); - } - else - alert("Invalid RSA public key"); -} - -// Perform raw public operation on "x": return x^e (mod n) -function RSADoPublic(x) { - return x.modPowInt(this.e, this.n); -} - -// Return the PKCS#1 RSA encryption of "text" as an even-length hex string -function RSAEncrypt(text) { - var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); - if(m == null) return null; - var c = this.doPublic(m); - if(c == null) return null; - var h = c.toString(16); - if((h.length & 1) == 0) return h; else return "0" + h; -} - -// Return the PKCS#1 OAEP RSA encryption of "text" as an even-length hex string -function RSAEncryptOAEP(text, hash) { - var m = oaep_pad(text, (this.n.bitLength()+7)>>3, hash); - if(m == null) return null; - var c = this.doPublic(m); - if(c == null) return null; - var h = c.toString(16); - if((h.length & 1) == 0) return h; else return "0" + h; -} - -// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string -//function RSAEncryptB64(text) { -// var h = this.encrypt(text); -// if(h) return hex2b64(h); else return null; -//} - -// protected -RSAKey.prototype.doPublic = RSADoPublic; - -// public -RSAKey.prototype.setPublic = RSASetPublic; -RSAKey.prototype.encrypt = RSAEncrypt; -RSAKey.prototype.encryptOAEP = RSAEncryptOAEP; -//RSAKey.prototype.encrypt_b64 = RSAEncryptB64; - -RSAKey.prototype.type = "RSA"; -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -// Depends on rsa.js and jsbn2.js - -// Version 1.1: support utf-8 decoding in pkcs1unpad2 - -// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext -function pkcs1unpad2(d,n) { - var b = d.toByteArray(); - var i = 0; - while(i < b.length && b[i] == 0) ++i; - if(b.length-i != n-1 || b[i] != 2) - return null; - ++i; - while(b[i] != 0) - if(++i >= b.length) return null; - var ret = ""; - while(++i < b.length) { - var c = b[i] & 255; - if(c < 128) { // utf-8 decode - ret += String.fromCharCode(c); - } - else if((c > 191) && (c < 224)) { - ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63)); - ++i; - } - else { - ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63)); - i += 2; - } - } - return ret; -} - -// PKCS#1 (OAEP) mask generation function -function oaep_mgf1_str(seed, len, hash) -{ - var mask = '', i = 0; - - while (mask.length < len) - { - mask += hash(seed + String.fromCharCode.apply(String, [ - (i & 0xff000000) >> 24, - (i & 0x00ff0000) >> 16, - (i & 0x0000ff00) >> 8, - i & 0x000000ff])); - i += 1; - } - - return mask; -} - -var SHA1_SIZE = 20; - -// Undo PKCS#1 (OAEP) padding and, if valid, return the plaintext -function oaep_unpad(d, n, hash) -{ - d = d.toByteArray(); - - var i; - - for (i = 0; i < d.length; i += 1) - { - d[i] &= 0xff; - } - - while (d.length < n) - { - d.unshift(0); - } - - d = String.fromCharCode.apply(String, d); - - if (d.length < 2 * SHA1_SIZE + 2) - { - throw "Cipher too short"; - } - - var maskedSeed = d.substr(1, SHA1_SIZE) - var maskedDB = d.substr(SHA1_SIZE + 1); - - var seedMask = oaep_mgf1_str(maskedDB, SHA1_SIZE, hash || rstr_sha1); - var seed = [], i; - - for (i = 0; i < maskedSeed.length; i += 1) - { - seed[i] = maskedSeed.charCodeAt(i) ^ seedMask.charCodeAt(i); - } - - var dbMask = oaep_mgf1_str(String.fromCharCode.apply(String, seed), - d.length - SHA1_SIZE, rstr_sha1); - - var DB = []; - - for (i = 0; i < maskedDB.length; i += 1) - { - DB[i] = maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i); - } - - DB = String.fromCharCode.apply(String, DB); - - if (DB.substr(0, SHA1_SIZE) !== rstr_sha1('')) - { - throw "Hash mismatch"; - } - - DB = DB.substr(SHA1_SIZE); - - var first_one = DB.indexOf('\x01'); - var last_zero = (first_one != -1) ? DB.substr(0, first_one).lastIndexOf('\x00') : -1; - - if (last_zero + 1 != first_one) - { - throw "Malformed data"; - } - - return DB.substr(first_one + 1); -} - -// Set the private key fields N, e, and d from hex strings -function RSASetPrivate(N,E,D) { - this.isPrivate = true; - if (typeof N !== "string") - { - this.n = N; - this.e = E; - this.d = D; - } - else if(N != null && E != null && N.length > 0 && E.length > 0) { - this.n = parseBigInt(N,16); - this.e = parseInt(E,16); - this.d = parseBigInt(D,16); - } - else - alert("Invalid RSA private key"); -} - -// Set the private key fields N, e, d and CRT params from hex strings -function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) { - this.isPrivate = true; - if (N == null) throw "RSASetPrivateEx N == null"; - if (E == null) throw "RSASetPrivateEx E == null"; - if (N.length == 0) throw "RSASetPrivateEx N.length == 0"; - if (E.length == 0) throw "RSASetPrivateEx E.length == 0"; - - if (N != null && E != null && N.length > 0 && E.length > 0) { - this.n = parseBigInt(N,16); - this.e = parseInt(E,16); - this.d = parseBigInt(D,16); - this.p = parseBigInt(P,16); - this.q = parseBigInt(Q,16); - this.dmp1 = parseBigInt(DP,16); - this.dmq1 = parseBigInt(DQ,16); - this.coeff = parseBigInt(C,16); - } else { - alert("Invalid RSA private key in RSASetPrivateEx"); - } -} - -// Generate a new random private key B bits long, using public expt E -function RSAGenerate(B,E) { - var rng = new SecureRandom(); - var qs = B>>1; - this.e = parseInt(E,16); - var ee = new BigInteger(E,16); - for(;;) { - for(;;) { - this.p = new BigInteger(B-qs,1,rng); - if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; - } - for(;;) { - this.q = new BigInteger(qs,1,rng); - if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break; - } - if(this.p.compareTo(this.q) <= 0) { - var t = this.p; - this.p = this.q; - this.q = t; - } - var p1 = this.p.subtract(BigInteger.ONE); // p1 = p - 1 - var q1 = this.q.subtract(BigInteger.ONE); // q1 = q - 1 - var phi = p1.multiply(q1); - if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { - this.n = this.p.multiply(this.q); // this.n = p * q - this.d = ee.modInverse(phi); // this.d = - this.dmp1 = this.d.mod(p1); // this.dmp1 = d mod (p - 1) - this.dmq1 = this.d.mod(q1); // this.dmq1 = d mod (q - 1) - this.coeff = this.q.modInverse(this.p); // this.coeff = (q ^ -1) mod p - break; - } - } - this.isPrivate = true; -} - -// Perform raw private operation on "x": return x^d (mod n) -function RSADoPrivate(x) { - if(this.p == null || this.q == null) - return x.modPow(this.d, this.n); - - // TODO: re-calculate any missing CRT params - var xp = x.mod(this.p).modPow(this.dmp1, this.p); // xp=cp? - var xq = x.mod(this.q).modPow(this.dmq1, this.q); // xq=cq? - - while(xp.compareTo(xq) < 0) - xp = xp.add(this.p); - // NOTE: - // xp.subtract(xq) => cp -cq - // xp.subtract(xq).multiply(this.coeff).mod(this.p) => (cp - cq) * u mod p = h - // xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq) => cq + (h * q) = M - return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); -} - -// Return the PKCS#1 RSA decryption of "ctext". -// "ctext" is an even-length hex string and the output is a plain string. -function RSADecrypt(ctext) { - var c = parseBigInt(ctext, 16); - var m = this.doPrivate(c); - if(m == null) return null; - return pkcs1unpad2(m, (this.n.bitLength()+7)>>3); -} - -// Return the PKCS#1 OAEP RSA decryption of "ctext". -// "ctext" is an even-length hex string and the output is a plain string. -function RSADecryptOAEP(ctext, hash) { - var c = parseBigInt(ctext, 16); - var m = this.doPrivate(c); - if(m == null) return null; - return oaep_unpad(m, (this.n.bitLength()+7)>>3, hash); -} - -// Return the PKCS#1 RSA decryption of "ctext". -// "ctext" is a Base64-encoded string and the output is a plain string. -//function RSAB64Decrypt(ctext) { -// var h = b64tohex(ctext); -// if(h) return this.decrypt(h); else return null; -//} - -// protected -RSAKey.prototype.doPrivate = RSADoPrivate; - -// public -RSAKey.prototype.setPrivate = RSASetPrivate; -RSAKey.prototype.setPrivateEx = RSASetPrivateEx; -RSAKey.prototype.generate = RSAGenerate; -RSAKey.prototype.decrypt = RSADecrypt; -RSAKey.prototype.decryptOAEP = RSADecryptOAEP; -//RSAKey.prototype.b64_decrypt = RSAB64Decrypt; -/*! rsapem-1.1.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -// -// rsa-pem.js - adding function for reading/writing PKCS#1 PEM private key -// to RSAKey class. -// -// version: 1.1.1 (2013-Apr-12) -// -// Copyright (c) 2010-2013 Kenji Urushima (kenji.urushima@gmail.com) -// -// This software is licensed under the terms of the MIT License. -// http://kjur.github.com/jsrsasign/license/ -// -// The above copyright and license notice shall be -// included in all copies or substantial portions of the Software. -// -// -// Depends on: -// -// -// -// _RSApem_pemToBase64(sPEM) -// -// removing PEM header, PEM footer and space characters including -// new lines from PEM formatted RSA private key string. -// - -/** - * @fileOverview - * @name rsapem-1.1.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version 1.1 - * @license MIT License - */ -function _rsapem_pemToBase64(sPEMPrivateKey) { - var s = sPEMPrivateKey; - s = s.replace("-----BEGIN RSA PRIVATE KEY-----", ""); - s = s.replace("-----END RSA PRIVATE KEY-----", ""); - s = s.replace(/[ \n]+/g, ""); - return s; -} - -function _rsapem_getPosArrayOfChildrenFromHex(hPrivateKey) { - var a = new Array(); - var v1 = ASN1HEX.getStartPosOfV_AtObj(hPrivateKey, 0); - var n1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, v1); - var e1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, n1); - var d1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, e1); - var p1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, d1); - var q1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, p1); - var dp1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, q1); - var dq1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, dp1); - var co1 = ASN1HEX.getPosOfNextSibling_AtObj(hPrivateKey, dq1); - a.push(v1, n1, e1, d1, p1, q1, dp1, dq1, co1); - return a; -} - -function _rsapem_getHexValueArrayOfChildrenFromHex(hPrivateKey) { - var posArray = _rsapem_getPosArrayOfChildrenFromHex(hPrivateKey); - var v = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[0]); - var n = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[1]); - var e = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[2]); - var d = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[3]); - var p = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[4]); - var q = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[5]); - var dp = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[6]); - var dq = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[7]); - var co = ASN1HEX.getHexOfV_AtObj(hPrivateKey, posArray[8]); - var a = new Array(); - a.push(v, n, e, d, p, q, dp, dq, co); - return a; -} - -/** - * read RSA private key from a ASN.1 hexadecimal string - * @name readPrivateKeyFromASN1HexString - * @memberOf RSAKey# - * @function - * @param {String} keyHex ASN.1 hexadecimal string of PKCS#1 private key. - * @since 1.1.1 - */ -function _rsapem_readPrivateKeyFromASN1HexString(keyHex) { - var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex); - this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]); -} - -/** - * read PKCS#1 private key from a string - * @name readPrivateKeyFromPEMString - * @memberOf RSAKey# - * @function - * @param {String} keyPEM string of PKCS#1 private key. - */ -function _rsapem_readPrivateKeyFromPEMString(keyPEM) { - var keyB64 = _rsapem_pemToBase64(keyPEM); - var keyHex = b64tohex(keyB64) // depends base64.js - var a = _rsapem_getHexValueArrayOfChildrenFromHex(keyHex); - this.setPrivateEx(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]); -} - -RSAKey.prototype.readPrivateKeyFromPEMString = _rsapem_readPrivateKeyFromPEMString; -RSAKey.prototype.readPrivateKeyFromASN1HexString = _rsapem_readPrivateKeyFromASN1HexString; -/*! rsasign-1.2.7.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -var _RE_HEXDECONLY=new RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(d,e,a){var b=function(f){return KJUR.crypto.Util.hashString(f,a)};var c=b(d);return KJUR.crypto.Util.getPaddedDigestInfoHex(c,a,e)}function _zeroPaddingOfSignature(e,d){var c="";var a=d/4-e.length;for(var b=0;b>24,(d&16711680)>>16,(d&65280)>>8,d&255]))));d+=1}return b}function _rsasign_signStringPSS(e,a,d){var c=function(f){return KJUR.crypto.Util.hashHex(f,a)};var b=c(rstrtohex(e));if(d===undefined){d=-1}return this.signWithMessageHashPSS(b,a,d)}function _rsasign_signWithMessageHashPSS(l,a,k){var b=hextorstr(l);var g=b.length;var m=this.n.bitLength()-1;var c=Math.ceil(m/8);var d;var o=function(i){return KJUR.crypto.Util.hashHex(i,a)};if(k===-1||k===undefined){k=g}else{if(k===-2){k=c-g-2}else{if(k<-2){throw"invalid salt length"}}}if(c<(g+k+2)){throw"data too long"}var f="";if(k>0){f=new Array(k);new SecureRandom().nextBytes(f);f=String.fromCharCode.apply(String,f)}var n=hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+b+f)));var j=[];for(d=0;d>(8*c-m))&255;q[0]&=~p;for(d=0;dthis.n.bitLength()){return 0}var i=this.doPublic(b);var e=i.toString(16).replace(/^1f+00/,"");var g=_rsasign_getAlgNameAndHashFromHexDisgestInfo(e);if(g.length==0){return false}var d=g[0];var h=g[1];var a=function(k){return KJUR.crypto.Util.hashString(k,d)};var c=a(f);return(h==c)}function _rsasign_verifyWithMessageHash(e,a){a=a.replace(_RE_HEXDECONLY,"");a=a.replace(/[ \n]+/g,"");var b=parseBigInt(a,16);if(b.bitLength()>this.n.bitLength()){return 0}var h=this.doPublic(b);var g=h.toString(16).replace(/^1f+00/,"");var c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(g);if(c.length==0){return false}var d=c[0];var f=c[1];return(f==e)}function _rsasign_verifyStringPSS(c,b,a,f){var e=function(g){return KJUR.crypto.Util.hashHex(g,a)};var d=e(rstrtohex(c));if(f===undefined){f=-1}return this.verifyWithMessageHashPSS(d,b,a,f)}function _rsasign_verifyWithMessageHashPSS(f,s,l,c){var k=new BigInteger(s,16);if(k.bitLength()>this.n.bitLength()){return false}var r=function(i){return KJUR.crypto.Util.hashHex(i,l)};var j=hextorstr(f);var h=j.length;var g=this.n.bitLength()-1;var m=Math.ceil(g/8);var q;if(c===-1||c===undefined){c=h}else{if(c===-2){c=m-h-2}else{if(c<-2){throw"invalid salt length"}}}if(m<(h+c+2)){throw"data too long"}var a=this.doPublic(k).toByteArray();for(q=0;q>(8*m-g))&255;if((d.charCodeAt(0)&p)!==0){throw"bits beyond keysize not zero"}var n=pss_mgf1_str(e,d.length,r);var o=[];for(q=0;qMIT License - */ - -/* - * MEMO: - * f('3082025b02...', 2) ... 82025b ... 3bytes - * f('020100', 2) ... 01 ... 1byte - * f('0203001...', 2) ... 03 ... 1byte - * f('02818003...', 2) ... 8180 ... 2bytes - * f('3080....0000', 2) ... 80 ... -1 - * - * Requirements: - * - ASN.1 type octet length MUST be 1. - * (i.e. ASN.1 primitives like SET, SEQUENCE, INTEGER, OCTETSTRING ...) - */ - -/** - * ASN.1 DER encoded hexadecimal string utility class - * @name ASN1HEX - * @class ASN.1 DER encoded hexadecimal string utility class - * @since jsrsasign 1.1 - */ -var ASN1HEX = new function() { - /** - * get byte length for ASN.1 L(length) bytes - * @name getByteLengthOfL_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return byte length for ASN.1 L(length) bytes - */ - this.getByteLengthOfL_AtObj = function(s, pos) { - if (s.substring(pos + 2, pos + 3) != '8') return 1; - var i = parseInt(s.substring(pos + 3, pos + 4)); - if (i == 0) return -1; // length octet '80' indefinite length - if (0 < i && i < 10) return i + 1; // including '8?' octet; - return -2; // malformed format - }; - - /** - * get hexadecimal string for ASN.1 L(length) bytes - * @name getHexOfL_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return {String} hexadecimal string for ASN.1 L(length) bytes - */ - this.getHexOfL_AtObj = function(s, pos) { - var len = this.getByteLengthOfL_AtObj(s, pos); - if (len < 1) return ''; - return s.substring(pos + 2, pos + 2 + len * 2); - }; - - // getting ASN.1 length value at the position 'idx' of - // hexa decimal string 's'. - // - // f('3082025b02...', 0) ... 82025b ... ??? - // f('020100', 0) ... 01 ... 1 - // f('0203001...', 0) ... 03 ... 3 - // f('02818003...', 0) ... 8180 ... 128 - /** - * get integer value of ASN.1 length for ASN.1 data - * @name getIntOfL_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return ASN.1 L(length) integer value - */ - this.getIntOfL_AtObj = function(s, pos) { - var hLength = this.getHexOfL_AtObj(s, pos); - if (hLength == '') return -1; - var bi; - if (parseInt(hLength.substring(0, 1)) < 8) { - bi = new BigInteger(hLength, 16); - } else { - bi = new BigInteger(hLength.substring(2), 16); - } - return bi.intValue(); - }; - - /** - * get ASN.1 value starting string position for ASN.1 object refered by index 'idx'. - * @name getStartPosOfV_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - */ - this.getStartPosOfV_AtObj = function(s, pos) { - var l_len = this.getByteLengthOfL_AtObj(s, pos); - if (l_len < 0) return l_len; - return pos + (l_len + 1) * 2; - }; - - /** - * get hexadecimal string of ASN.1 V(value) - * @name getHexOfV_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return {String} hexadecimal string of ASN.1 value. - */ - this.getHexOfV_AtObj = function(s, pos) { - var pos1 = this.getStartPosOfV_AtObj(s, pos); - var len = this.getIntOfL_AtObj(s, pos); - return s.substring(pos1, pos1 + len * 2); - }; - - /** - * get hexadecimal string of ASN.1 TLV at - * @name getHexOfTLV_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return {String} hexadecimal string of ASN.1 TLV. - * @since 1.1 - */ - this.getHexOfTLV_AtObj = function(s, pos) { - var hT = s.substr(pos, 2); - var hL = this.getHexOfL_AtObj(s, pos); - var hV = this.getHexOfV_AtObj(s, pos); - return hT + hL + hV; - }; - - /** - * get next sibling starting index for ASN.1 object string - * @name getPosOfNextSibling_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} pos string index - * @return next sibling starting index for ASN.1 object string - */ - this.getPosOfNextSibling_AtObj = function(s, pos) { - var pos1 = this.getStartPosOfV_AtObj(s, pos); - var len = this.getIntOfL_AtObj(s, pos); - return pos1 + len * 2; - }; - - /** - * get array of indexes of child ASN.1 objects - * @name getPosArrayOfChildren_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} s hexadecimal string of ASN.1 DER encoded data - * @param {Number} start string index of ASN.1 object - * @return {Array of Number} array of indexes for childen of ASN.1 objects - */ - this.getPosArrayOfChildren_AtObj = function(h, pos) { - var a = new Array(); - var p0 = this.getStartPosOfV_AtObj(h, pos); - a.push(p0); - - var len = this.getIntOfL_AtObj(h, pos); - var p = p0; - var k = 0; - while (1) { - var pNext = this.getPosOfNextSibling_AtObj(h, p); - if (pNext == null || (pNext - p0 >= (len * 2))) break; - if (k >= 200) break; - - a.push(pNext); - p = pNext; - - k++; - } - - return a; - }; - - /** - * get string index of nth child object of ASN.1 object refered by h, idx - * @name getNthChildIndex_AtObj - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} idx start string index of ASN.1 object - * @param {Number} nth for child - * @return {Number} string index of nth child. - * @since 1.1 - */ - this.getNthChildIndex_AtObj = function(h, idx, nth) { - var a = this.getPosArrayOfChildren_AtObj(h, idx); - return a[nth]; - }; - - // ========== decendant methods ============================== - /** - * get string index of nth child object of ASN.1 object refered by h, idx - * @name getDecendantIndexByNthList - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} currentIndex start string index of ASN.1 object - * @param {Array of Number} nthList array list of nth - * @return {Number} string index refered by nthList - * @since 1.1 - * @example - * The "nthList" is a index list of structured ASN.1 object - * reference. Here is a sample structure and "nthList"s which - * refers each objects. - * - * SQUENCE - - * SEQUENCE - [0] - * IA5STRING 000 - [0, 0] - * UTF8STRING 001 - [0, 1] - * SET - [1] - * IA5STRING 010 - [1, 0] - * UTF8STRING 011 - [1, 1] - */ - this.getDecendantIndexByNthList = function(h, currentIndex, nthList) { - if (nthList.length == 0) { - return currentIndex; - } - var firstNth = nthList.shift(); - var a = this.getPosArrayOfChildren_AtObj(h, currentIndex); - return this.getDecendantIndexByNthList(h, a[firstNth], nthList); - }; - - /** - * get hexadecimal string of ASN.1 TLV refered by current index and nth index list. - * @name getDecendantHexTLVByNthList - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} currentIndex start string index of ASN.1 object - * @param {Array of Number} nthList array list of nth - * @return {Number} hexadecimal string of ASN.1 TLV refered by nthList - * @since 1.1 - */ - this.getDecendantHexTLVByNthList = function(h, currentIndex, nthList) { - var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList); - return this.getHexOfTLV_AtObj(h, idx); - }; - - /** - * get hexadecimal string of ASN.1 V refered by current index and nth index list. - * @name getDecendantHexVByNthList - * @memberOf ASN1HEX - * @function - * @param {String} h hexadecimal string of ASN.1 DER encoded data - * @param {Number} currentIndex start string index of ASN.1 object - * @param {Array of Number} nthList array list of nth - * @return {Number} hexadecimal string of ASN.1 V refered by nthList - * @since 1.1 - */ - this.getDecendantHexVByNthList = function(h, currentIndex, nthList) { - var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList); - return this.getHexOfV_AtObj(h, idx); - }; -}; - -/* - * @since asn1hex 1.1.4 - */ -ASN1HEX.getVbyList = function(h, currentIndex, nthList, checkingTag) { - var idx = this.getDecendantIndexByNthList(h, currentIndex, nthList); - if (idx === undefined) { - throw "can't find nthList object"; - } - if (checkingTag !== undefined) { - if (h.substr(idx, 2) != checkingTag) { - throw "checking tag doesn't match: " + - h.substr(idx,2) + "!=" + checkingTag; - } - } - return this.getHexOfV_AtObj(h, idx); -}; - -/** - * get OID string from hexadecimal encoded value - * @name hextooidstr - * @memberOf ASN1HEX - * @function - * @param {String} hex hexadecmal string of ASN.1 DER encoded OID value - * @return {String} OID string (ex. '1.2.3.4.567') - * @since asn1hex 1.1.5 - */ -ASN1HEX.hextooidstr = function(hex) { - var zeroPadding = function(s, len) { - if (s.length >= len) return s; - return new Array(len - s.length + 1).join('0') + s; - }; - - var a = []; - - // a[0], a[1] - var hex0 = hex.substr(0, 2); - var i0 = parseInt(hex0, 16); - a[0] = new String(Math.floor(i0 / 40)); - a[1] = new String(i0 % 40); - - // a[2]..a[n] - var hex1 = hex.substr(2); - var b = []; - for (var i = 0; i < hex1.length / 2; i++) { - b.push(parseInt(hex1.substr(i * 2, 2), 16)); - } - var c = []; - var cbin = ""; - for (var i = 0; i < b.length; i++) { - if (b[i] & 0x80) { - cbin = cbin + zeroPadding((b[i] & 0x7f).toString(2), 7); - } else { - cbin = cbin + zeroPadding((b[i] & 0x7f).toString(2), 7); - c.push(new String(parseInt(cbin, 2))); - cbin = ""; - } - } - - var s = a.join("."); - if (c.length > 0) s = s + "." + c.join("."); - return s; -}; - -/*! x509-1.1.3.js (c) 2012-2014 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -/* - * x509.js - X509 class to read subject public key from certificate. - * - * Copyright (c) 2010-2014 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsrsasign/license - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - */ - -/** - * @fileOverview - * @name x509-1.1.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version x509 1.1.3 (2014-May-17) - * @since jsrsasign 1.x.x - * @license MIT License - */ - -/* - * Depends: - * base64.js - * rsa.js - * asn1hex.js - */ - -/** - * X.509 certificate class.
- * @class X.509 certificate class - * @property {RSAKey} subjectPublicKeyRSA Tom Wu's RSAKey object - * @property {String} subjectPublicKeyRSA_hN hexadecimal string for modulus of RSA public key - * @property {String} subjectPublicKeyRSA_hE hexadecimal string for public exponent of RSA public key - * @property {String} hex hexacedimal string for X.509 certificate. - * @author Kenji Urushima - * @version 1.0.1 (08 May 2012) - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - */ -function X509() { - this.subjectPublicKeyRSA = null; - this.subjectPublicKeyRSA_hN = null; - this.subjectPublicKeyRSA_hE = null; - this.hex = null; - - // ===== get basic fields from hex ===================================== - - /** - * get hexadecimal string of serialNumber field of certificate.
- * @name getSerialNumberHex - * @memberOf X509# - * @function - */ - this.getSerialNumberHex = function() { - return ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 1]); - }; - - /** - * get hexadecimal string of issuer field TLV of certificate.
- * @name getIssuerHex - * @memberOf X509# - * @function - */ - this.getIssuerHex = function() { - return ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 3]); - }; - - /** - * get string of issuer field of certificate.
- * @name getIssuerString - * @memberOf X509# - * @function - */ - this.getIssuerString = function() { - return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 3])); - }; - - /** - * get hexadecimal string of subject field of certificate.
- * @name getSubjectHex - * @memberOf X509# - * @function - */ - this.getSubjectHex = function() { - return ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 5]); - }; - - /** - * get string of subject field of certificate.
- * @name getSubjectString - * @memberOf X509# - * @function - */ - this.getSubjectString = function() { - return X509.hex2dn(ASN1HEX.getDecendantHexTLVByNthList(this.hex, 0, [0, 5])); - }; - - /** - * get notBefore field string of certificate.
- * @name getNotBefore - * @memberOf X509# - * @function - */ - this.getNotBefore = function() { - var s = ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 4, 0]); - s = s.replace(/(..)/g, "%$1"); - s = decodeURIComponent(s); - return s; - }; - - /** - * get notAfter field string of certificate.
- * @name getNotAfter - * @memberOf X509# - * @function - */ - this.getNotAfter = function() { - var s = ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 4, 1]); - s = s.replace(/(..)/g, "%$1"); - s = decodeURIComponent(s); - return s; - }; - - // ===== read certificate public key ========================== - - // ===== read certificate ===================================== - /** - * read PEM formatted X.509 certificate from string.
- * @name readCertPEM - * @memberOf X509# - * @function - * @param {String} sCertPEM string for PEM formatted X.509 certificate - */ - this.readCertPEM = function(sCertPEM) { - var hCert = X509.pemToHex(sCertPEM); - var a = X509.getPublicKeyHexArrayFromCertHex(hCert); - var rsa = new RSAKey(); - rsa.setPublic(a[0], a[1]); - this.subjectPublicKeyRSA = rsa; - this.subjectPublicKeyRSA_hN = a[0]; - this.subjectPublicKeyRSA_hE = a[1]; - this.hex = hCert; - }; - - this.readCertPEMWithoutRSAInit = function(sCertPEM) { - var hCert = X509.pemToHex(sCertPEM); - var a = X509.getPublicKeyHexArrayFromCertHex(hCert); - this.subjectPublicKeyRSA.setPublic(a[0], a[1]); - this.subjectPublicKeyRSA_hN = a[0]; - this.subjectPublicKeyRSA_hE = a[1]; - this.hex = hCert; - }; -}; - -X509.pemToBase64 = function(sCertPEM) { - var s = sCertPEM; - s = s.replace("-----BEGIN CERTIFICATE-----", ""); - s = s.replace("-----END CERTIFICATE-----", ""); - s = s.replace(/[ \n]+/g, ""); - return s; -}; - -X509.pemToHex = function(sCertPEM) { - var b64Cert = X509.pemToBase64(sCertPEM); - var hCert = b64tohex(b64Cert); - return hCert; -}; - -// NOTE: Without BITSTRING encapsulation. -X509.getSubjectPublicKeyPosFromCertHex = function(hCert) { - var pInfo = X509.getSubjectPublicKeyInfoPosFromCertHex(hCert); - if (pInfo == -1) return -1; - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pInfo); - if (a.length != 2) return -1; - var pBitString = a[1]; - if (hCert.substring(pBitString, pBitString + 2) != '03') return -1; - var pBitStringV = ASN1HEX.getStartPosOfV_AtObj(hCert, pBitString); - - if (hCert.substring(pBitStringV, pBitStringV + 2) != '00') return -1; - return pBitStringV + 2; -}; - -// NOTE: privateKeyUsagePeriod field of X509v2 not supported. -// NOTE: v1 and v3 supported -X509.getSubjectPublicKeyInfoPosFromCertHex = function(hCert) { - var pTbsCert = ASN1HEX.getStartPosOfV_AtObj(hCert, 0); - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, pTbsCert); - if (a.length < 1) return -1; - if (hCert.substring(a[0], a[0] + 10) == "a003020102") { // v3 - if (a.length < 6) return -1; - return a[6]; - } else { - if (a.length < 5) return -1; - return a[5]; - } -}; - -X509.getPublicKeyHexArrayFromCertHex = function(hCert) { - var p = X509.getSubjectPublicKeyPosFromCertHex(hCert); - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, p); - if (a.length != 2) return []; - var hN = ASN1HEX.getHexOfV_AtObj(hCert, a[0]); - var hE = ASN1HEX.getHexOfV_AtObj(hCert, a[1]); - if (hN != null && hE != null) { - return [hN, hE]; - } else { - return []; - } -}; - -X509.getHexTbsCertificateFromCert = function(hCert) { - var pTbsCert = ASN1HEX.getStartPosOfV_AtObj(hCert, 0); - return pTbsCert; -}; - -X509.getPublicKeyHexArrayFromCertPEM = function(sCertPEM) { - var hCert = X509.pemToHex(sCertPEM); - var a = X509.getPublicKeyHexArrayFromCertHex(hCert); - return a; -}; - -X509.hex2dn = function(hDN) { - var s = ""; - var a = ASN1HEX.getPosArrayOfChildren_AtObj(hDN, 0); - for (var i = 0; i < a.length; i++) { - var hRDN = ASN1HEX.getHexOfTLV_AtObj(hDN, a[i]); - s = s + "/" + X509.hex2rdn(hRDN); - } - return s; -}; - -X509.hex2rdn = function(hRDN) { - var hType = ASN1HEX.getDecendantHexTLVByNthList(hRDN, 0, [0, 0]); - var hValue = ASN1HEX.getDecendantHexVByNthList(hRDN, 0, [0, 1]); - var type = ""; - try { type = X509.DN_ATTRHEX[hType]; } catch (ex) { type = hType; } - hValue = hValue.replace(/(..)/g, "%$1"); - var value = decodeURIComponent(hValue); - return type + "=" + value; -}; - -X509.DN_ATTRHEX = { - "0603550406": "C", - "060355040a": "O", - "060355040b": "OU", - "0603550403": "CN", - "0603550405": "SN", - "0603550408": "ST", - "0603550407": "L", -}; - -/** - * get RSAKey/ECDSA public key object from PEM certificate string - * @name getPublicKeyFromCertPEM - * @memberOf X509 - * @function - * @param {String} sCertPEM PEM formatted RSA/ECDSA/DSA X.509 certificate - * @return returns RSAKey/KJUR.crypto.{ECDSA,DSA} object of public key - * @since x509 1.1.1 - * @description - * NOTE: DSA is also supported since x509 1.1.2. - */ -X509.getPublicKeyFromCertPEM = function(sCertPEM) { - var info = X509.getPublicKeyInfoPropOfCertPEM(sCertPEM); - - if (info.algoid == "2a864886f70d010101") { // RSA - var aRSA = KEYUTIL.parsePublicRawRSAKeyHex(info.keyhex); - var key = new RSAKey(); - key.setPublic(aRSA.n, aRSA.e); - return key; - } else if (info.algoid == "2a8648ce3d0201") { // ECC - var curveName = KJUR.crypto.OID.oidhex2name[info.algparam]; - var key = new KJUR.crypto.ECDSA({'curve': curveName, 'info': info.keyhex}); - key.setPublicKeyHex(info.keyhex); - return key; - } else if (info.algoid == "2a8648ce380401") { // DSA 1.2.840.10040.4.1 - var p = ASN1HEX.getVbyList(info.algparam, 0, [0], "02"); - var q = ASN1HEX.getVbyList(info.algparam, 0, [1], "02"); - var g = ASN1HEX.getVbyList(info.algparam, 0, [2], "02"); - var y = ASN1HEX.getHexOfV_AtObj(info.keyhex, 0); - y = y.substr(2); - var key = new KJUR.crypto.DSA(); - key.setPublic(new BigInteger(p, 16), - new BigInteger(q, 16), - new BigInteger(g, 16), - new BigInteger(y, 16)); - return key; - } else { - throw "unsupported key"; - } -}; - -/** - * get public key information from PEM certificate - * @name getPublicKeyInfoPropOfCertPEM - * @memberOf X509 - * @function - * @param {String} sCertPEM string of PEM formatted certificate - * @return {Hash} hash of information for public key - * @since x509 1.1.1 - * @description - * Resulted associative array has following properties: - *
    - *
  • algoid - hexadecimal string of OID of asymmetric key algorithm
  • - *
  • algparam - hexadecimal string of OID of ECC curve name or null
  • - *
  • keyhex - hexadecimal string of key in the certificate
  • - *
- * @since x509 1.1.1 - */ -X509.getPublicKeyInfoPropOfCertPEM = function(sCertPEM) { - var result = {}; - result.algparam = null; - var hCert = X509.pemToHex(sCertPEM); - - // 1. Certificate ASN.1 - var a1 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, 0); - if (a1.length != 3) - throw "malformed X.509 certificate PEM (code:001)"; // not 3 item of seq Cert - - // 2. tbsCertificate - if (hCert.substr(a1[0], 2) != "30") - throw "malformed X.509 certificate PEM (code:002)"; // tbsCert not seq - - var a2 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a1[0]); - - // 3. subjectPublicKeyInfo - if (a2.length < 7) - throw "malformed X.509 certificate PEM (code:003)"; // no subjPubKeyInfo - - var a3 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a2[6]); - - if (a3.length != 2) - throw "malformed X.509 certificate PEM (code:004)"; // not AlgId and PubKey - - // 4. AlgId - var a4 = ASN1HEX.getPosArrayOfChildren_AtObj(hCert, a3[0]); - - if (a4.length != 2) - throw "malformed X.509 certificate PEM (code:005)"; // not 2 item in AlgId - - result.algoid = ASN1HEX.getHexOfV_AtObj(hCert, a4[0]); - - if (hCert.substr(a4[1], 2) == "06") { // EC - result.algparam = ASN1HEX.getHexOfV_AtObj(hCert, a4[1]); - } else if (hCert.substr(a4[1], 2) == "30") { // DSA - result.algparam = ASN1HEX.getHexOfTLV_AtObj(hCert, a4[1]); - } - - // 5. Public Key Hex - if (hCert.substr(a3[1], 2) != "03") - throw "malformed X.509 certificate PEM (code:006)"; // not bitstring - - var unusedBitAndKeyHex = ASN1HEX.getHexOfV_AtObj(hCert, a3[1]); - result.keyhex = unusedBitAndKeyHex.substr(2); - - return result; -}; - -/* - X509.prototype.readCertPEM = _x509_readCertPEM; - X509.prototype.readCertPEMWithoutRSAInit = _x509_readCertPEMWithoutRSAInit; - X509.prototype.getSerialNumberHex = _x509_getSerialNumberHex; - X509.prototype.getIssuerHex = _x509_getIssuerHex; - X509.prototype.getSubjectHex = _x509_getSubjectHex; - X509.prototype.getIssuerString = _x509_getIssuerString; - X509.prototype.getSubjectString = _x509_getSubjectString; - X509.prototype.getNotBefore = _x509_getNotBefore; - X509.prototype.getNotAfter = _x509_getNotAfter; -*/ -/*! crypto-1.1.5.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license - */ -/* - * crypto.js - Cryptographic Algorithm Provider class - * - * Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsrsasign/license - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - */ - -/** - * @fileOverview - * @name crypto-1.1.js - * @author Kenji Urushima kenji.urushima@gmail.com - * @version 1.1.5 (2013-Oct-06) - * @since jsrsasign 2.2 - * @license MIT License - */ - -/** - * kjur's class library name space - * @name KJUR - * @namespace kjur's class library name space - */ -if (typeof KJUR == "undefined" || !KJUR) KJUR = {}; -/** - * kjur's cryptographic algorithm provider library name space - *

- * This namespace privides following crytpgrahic classes. - *

    - *
  • {@link KJUR.crypto.MessageDigest} - Java JCE(cryptograhic extension) style MessageDigest class
  • - *
  • {@link KJUR.crypto.Signature} - Java JCE(cryptograhic extension) style Signature class
  • - *
  • {@link KJUR.crypto.Util} - cryptographic utility functions and properties
  • - *
- * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. - *

- * @name KJUR.crypto - * @namespace - */ -if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) KJUR.crypto = {}; - -/** - * static object for cryptographic function utilities - * @name KJUR.crypto.Util - * @class static object for cryptographic function utilities - * @property {Array} DIGESTINFOHEAD PKCS#1 DigestInfo heading hexadecimal bytes for each hash algorithms - * @property {Array} DEFAULTPROVIDER associative array of default provider name for each hash and signature algorithms - * @description - */ -KJUR.crypto.Util = new function() { - this.DIGESTINFOHEAD = { - 'sha1': "3021300906052b0e03021a05000414", - 'sha224': "302d300d06096086480165030402040500041c", - 'sha256': "3031300d060960864801650304020105000420", - 'sha384': "3041300d060960864801650304020205000430", - 'sha512': "3051300d060960864801650304020305000440", - 'md2': "3020300c06082a864886f70d020205000410", - 'md5': "3020300c06082a864886f70d020505000410", - 'ripemd160': "3021300906052b2403020105000414", - }; - - /* - * @since crypto 1.1.1 - */ - this.DEFAULTPROVIDER = { - 'md5': 'cryptojs', - 'sha1': 'cryptojs', - 'sha224': 'cryptojs', - 'sha256': 'cryptojs', - 'sha384': 'cryptojs', - 'sha512': 'cryptojs', - 'ripemd160': 'cryptojs', - 'hmacmd5': 'cryptojs', - 'hmacsha1': 'cryptojs', - 'hmacsha224': 'cryptojs', - 'hmacsha256': 'cryptojs', - 'hmacsha384': 'cryptojs', - 'hmacsha512': 'cryptojs', - 'hmacripemd160': 'cryptojs', - - 'MD5withRSA': 'cryptojs/jsrsa', - 'SHA1withRSA': 'cryptojs/jsrsa', - 'SHA224withRSA': 'cryptojs/jsrsa', - 'SHA256withRSA': 'cryptojs/jsrsa', - 'SHA384withRSA': 'cryptojs/jsrsa', - 'SHA512withRSA': 'cryptojs/jsrsa', - 'RIPEMD160withRSA': 'cryptojs/jsrsa', - - 'MD5withECDSA': 'cryptojs/jsrsa', - 'SHA1withECDSA': 'cryptojs/jsrsa', - 'SHA224withECDSA': 'cryptojs/jsrsa', - 'SHA256withECDSA': 'cryptojs/jsrsa', - 'SHA384withECDSA': 'cryptojs/jsrsa', - 'SHA512withECDSA': 'cryptojs/jsrsa', - 'RIPEMD160withECDSA': 'cryptojs/jsrsa', - - 'SHA1withDSA': 'cryptojs/jsrsa', - 'SHA224withDSA': 'cryptojs/jsrsa', - 'SHA256withDSA': 'cryptojs/jsrsa', - - 'MD5withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA1withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA224withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA256withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA384withRSAandMGF1': 'cryptojs/jsrsa', - 'SHA512withRSAandMGF1': 'cryptojs/jsrsa', - 'RIPEMD160withRSAandMGF1': 'cryptojs/jsrsa', - }; - - /* - * @since crypto 1.1.2 - */ - this.CRYPTOJSMESSAGEDIGESTNAME = { - 'md5': 'CryptoJS.algo.MD5', - 'sha1': 'CryptoJS.algo.SHA1', - 'sha224': 'CryptoJS.algo.SHA224', - 'sha256': 'CryptoJS.algo.SHA256', - 'sha384': 'CryptoJS.algo.SHA384', - 'sha512': 'CryptoJS.algo.SHA512', - 'ripemd160': 'CryptoJS.algo.RIPEMD160' - }; - - /** - * get hexadecimal DigestInfo - * @name getDigestInfoHex - * @memberOf KJUR.crypto.Util - * @function - * @param {String} hHash hexadecimal hash value - * @param {String} alg hash algorithm name (ex. 'sha1') - * @return {String} hexadecimal string DigestInfo ASN.1 structure - */ - this.getDigestInfoHex = function(hHash, alg) { - if (typeof this.DIGESTINFOHEAD[alg] == "undefined") - throw "alg not supported in Util.DIGESTINFOHEAD: " + alg; - return this.DIGESTINFOHEAD[alg] + hHash; - }; - - /** - * get PKCS#1 padded hexadecimal DigestInfo - * @name getPaddedDigestInfoHex - * @memberOf KJUR.crypto.Util - * @function - * @param {String} hHash hexadecimal hash value of message to be signed - * @param {String} alg hash algorithm name (ex. 'sha1') - * @param {Integer} keySize key bit length (ex. 1024) - * @return {String} hexadecimal string of PKCS#1 padded DigestInfo - */ - this.getPaddedDigestInfoHex = function(hHash, alg, keySize) { - var hDigestInfo = this.getDigestInfoHex(hHash, alg); - var pmStrLen = keySize / 4; // minimum PM length - - if (hDigestInfo.length + 22 > pmStrLen) // len(0001+ff(*8)+00+hDigestInfo)=22 - throw "key is too short for SigAlg: keylen=" + keySize + "," + alg; - - var hHead = "0001"; - var hTail = "00" + hDigestInfo; - var hMid = ""; - var fLen = pmStrLen - hHead.length - hTail.length; - for (var i = 0; i < fLen; i += 2) { - hMid += "ff"; - } - var hPaddedMessage = hHead + hMid + hTail; - return hPaddedMessage; - }; - - /** - * get hexadecimal hash of string with specified algorithm - * @name hashString - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @param {String} alg hash algorithm name - * @return {String} hexadecimal string of hash value - * @since 1.1.1 - */ - this.hashString = function(s, alg) { - var md = new KJUR.crypto.MessageDigest({'alg': alg}); - return md.digestString(s); - }; - - /** - * get hexadecimal hash of hexadecimal string with specified algorithm - * @name hashHex - * @memberOf KJUR.crypto.Util - * @function - * @param {String} sHex input hexadecimal string to be hashed - * @param {String} alg hash algorithm name - * @return {String} hexadecimal string of hash value - * @since 1.1.1 - */ - this.hashHex = function(sHex, alg) { - var md = new KJUR.crypto.MessageDigest({'alg': alg}); - return md.digestHex(sHex); - }; - - /** - * get hexadecimal SHA1 hash of string - * @name sha1 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.sha1 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha1', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - /** - * get hexadecimal SHA256 hash of string - * @name sha256 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.sha256 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha256', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - this.sha256Hex = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha256', 'prov':'cryptojs'}); - return md.digestHex(s); - }; - - /** - * get hexadecimal SHA512 hash of string - * @name sha512 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.sha512 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha512', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - this.sha512Hex = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'sha512', 'prov':'cryptojs'}); - return md.digestHex(s); - }; - - /** - * get hexadecimal MD5 hash of string - * @name md5 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.md5 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'md5', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - /** - * get hexadecimal RIPEMD160 hash of string - * @name ripemd160 - * @memberOf KJUR.crypto.Util - * @function - * @param {String} s input string to be hashed - * @return {String} hexadecimal string of hash value - * @since 1.0.3 - */ - this.ripemd160 = function(s) { - var md = new KJUR.crypto.MessageDigest({'alg':'ripemd160', 'prov':'cryptojs'}); - return md.digestString(s); - }; - - /* - * @since 1.1.2 - */ - this.getCryptoJSMDByName = function(s) { - - }; -}; - -/** - * MessageDigest class which is very similar to java.security.MessageDigest class - * @name KJUR.crypto.MessageDigest - * @class MessageDigest class which is very similar to java.security.MessageDigest class - * @param {Array} params parameters for constructor - * @description - *
- * Currently this supports following algorithm and providers combination: - *
    - *
  • md5 - cryptojs
  • - *
  • sha1 - cryptojs
  • - *
  • sha224 - cryptojs
  • - *
  • sha256 - cryptojs
  • - *
  • sha384 - cryptojs
  • - *
  • sha512 - cryptojs
  • - *
  • ripemd160 - cryptojs
  • - *
  • sha256 - sjcl (NEW from crypto.js 1.0.4)
  • - *
- * @example - * // CryptoJS provider sample - * <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/core.js"></script> - * <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/sha1.js"></script> - * <script src="crypto-1.0.js"></script> - * var md = new KJUR.crypto.MessageDigest({alg: "sha1", prov: "cryptojs"}); - * md.updateString('aaa') - * var mdHex = md.digest() - * - * // SJCL(Stanford JavaScript Crypto Library) provider sample - * <script src="http://bitwiseshiftleft.github.io/sjcl/sjcl.js"></script> - * <script src="crypto-1.0.js"></script> - * var md = new KJUR.crypto.MessageDigest({alg: "sha256", prov: "sjcl"}); // sjcl supports sha256 only - * md.updateString('aaa') - * var mdHex = md.digest() - */ -KJUR.crypto.MessageDigest = function(params) { - var md = null; - var algName = null; - var provName = null; - - /** - * set hash algorithm and provider - * @name setAlgAndProvider - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} alg hash algorithm name - * @param {String} prov provider name - * @description - * @example - * // for SHA1 - * md.setAlgAndProvider('sha1', 'cryptojs'); - * // for RIPEMD160 - * md.setAlgAndProvider('ripemd160', 'cryptojs'); - */ - this.setAlgAndProvider = function(alg, prov) { - if (alg != null && prov === undefined) prov = KJUR.crypto.Util.DEFAULTPROVIDER[alg]; - - // for cryptojs - if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(alg) != -1 && - prov == 'cryptojs') { - try { - this.md = eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[alg]).create(); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail alg=" + alg + "/" + ex; - } - this.updateString = function(str) { - this.md.update(str); - }; - this.updateHex = function(hex) { - var wHex = CryptoJS.enc.Hex.parse(hex); - this.md.update(wHex); - }; - this.digest = function() { - var hash = this.md.finalize(); - return hash.toString(CryptoJS.enc.Hex); - }; - this.digestString = function(str) { - this.updateString(str); - return this.digest(); - }; - this.digestHex = function(hex) { - this.updateHex(hex); - return this.digest(); - }; - } - if (':sha256:'.indexOf(alg) != -1 && - prov == 'sjcl') { - try { - this.md = new sjcl.hash.sha256(); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail alg=" + alg + "/" + ex; - } - this.updateString = function(str) { - this.md.update(str); - }; - this.updateHex = function(hex) { - var baHex = sjcl.codec.hex.toBits(hex); - this.md.update(baHex); - }; - this.digest = function() { - var hash = this.md.finalize(); - return sjcl.codec.hex.fromBits(hash); - }; - this.digestString = function(str) { - this.updateString(str); - return this.digest(); - }; - this.digestHex = function(hex) { - this.updateHex(hex); - return this.digest(); - }; - } - }; - - /** - * update digest by specified string - * @name updateString - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} str string to update - * @description - * @example - * md.updateString('New York'); - */ - this.updateString = function(str) { - throw "updateString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * update digest by specified hexadecimal string - * @name updateHex - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} hex hexadecimal string to update - * @description - * @example - * md.updateHex('0afe36'); - */ - this.updateHex = function(hex) { - throw "updateHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * completes hash calculation and returns hash result - * @name digest - * @memberOf KJUR.crypto.MessageDigest - * @function - * @description - * @example - * md.digest() - */ - this.digest = function() { - throw "digest() not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * performs final update on the digest using string, then completes the digest computation - * @name digestString - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} str string to final update - * @description - * @example - * md.digestString('aaa') - */ - this.digestString = function(str) { - throw "digestString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - /** - * performs final update on the digest using hexadecimal string, then completes the digest computation - * @name digestHex - * @memberOf KJUR.crypto.MessageDigest - * @function - * @param {String} hex hexadecimal string to final update - * @description - * @example - * md.digestHex('0f2abd') - */ - this.digestHex = function(hex) { - throw "digestHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName; - }; - - if (params !== undefined) { - if (params['alg'] !== undefined) { - this.algName = params['alg']; - if (params['prov'] === undefined) - this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]; - this.setAlgAndProvider(this.algName, this.provName); - } - } -}; - -/** - * Mac(Message Authentication Code) class which is very similar to java.security.Mac class - * @name KJUR.crypto.Mac - * @class Mac class which is very similar to java.security.Mac class - * @param {Array} params parameters for constructor - * @description - *
- * Currently this supports following algorithm and providers combination: - *
    - *
  • hmacmd5 - cryptojs
  • - *
  • hmacsha1 - cryptojs
  • - *
  • hmacsha224 - cryptojs
  • - *
  • hmacsha256 - cryptojs
  • - *
  • hmacsha384 - cryptojs
  • - *
  • hmacsha512 - cryptojs
  • - *
- * NOTE: HmacSHA224 and HmacSHA384 issue was fixed since jsrsasign 4.1.4. - * Please use 'ext/cryptojs-312-core-fix*.js' instead of 'core.js' of original CryptoJS - * to avoid those issue. - * @example - * var mac = new KJUR.crypto.Mac({alg: "HmacSHA1", prov: "cryptojs", "pass": "pass"}); - * mac.updateString('aaa') - * var macHex = md.doFinal() - */ -KJUR.crypto.Mac = function(params) { - var mac = null; - var pass = null; - var algName = null; - var provName = null; - var algProv = null; - - this.setAlgAndProvider = function(alg, prov) { - if (alg == null) alg = "hmacsha1"; - - alg = alg.toLowerCase(); - if (alg.substr(0, 4) != "hmac") { - throw "setAlgAndProvider unsupported HMAC alg: " + alg; - } - - if (prov === undefined) prov = KJUR.crypto.Util.DEFAULTPROVIDER[alg]; - this.algProv = alg + "/" + prov; - - var hashAlg = alg.substr(4); - - // for cryptojs - if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(hashAlg) != -1 && - prov == 'cryptojs') { - try { - var mdObj = eval(KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[hashAlg]); - this.mac = CryptoJS.algo.HMAC.create(mdObj, this.pass); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail hashAlg=" + hashAlg + "/" + ex; - } - this.updateString = function(str) { - this.mac.update(str); - }; - this.updateHex = function(hex) { - var wHex = CryptoJS.enc.Hex.parse(hex); - this.mac.update(wHex); - }; - this.doFinal = function() { - var hash = this.mac.finalize(); - return hash.toString(CryptoJS.enc.Hex); - }; - this.doFinalString = function(str) { - this.updateString(str); - return this.doFinal(); - }; - this.doFinalHex = function(hex) { - this.updateHex(hex); - return this.doFinal(); - }; - } - }; - - /** - * update digest by specified string - * @name updateString - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} str string to update - * @description - * @example - * md.updateString('New York'); - */ - this.updateString = function(str) { - throw "updateString(str) not supported for this alg/prov: " + this.algProv; - }; - - /** - * update digest by specified hexadecimal string - * @name updateHex - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} hex hexadecimal string to update - * @description - * @example - * md.updateHex('0afe36'); - */ - this.updateHex = function(hex) { - throw "updateHex(hex) not supported for this alg/prov: " + this.algProv; - }; - - /** - * completes hash calculation and returns hash result - * @name doFinal - * @memberOf KJUR.crypto.Mac - * @function - * @description - * @example - * md.digest() - */ - this.doFinal = function() { - throw "digest() not supported for this alg/prov: " + this.algProv; - }; - - /** - * performs final update on the digest using string, then completes the digest computation - * @name doFinalString - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} str string to final update - * @description - * @example - * md.digestString('aaa') - */ - this.doFinalString = function(str) { - throw "digestString(str) not supported for this alg/prov: " + this.algProv; - }; - - /** - * performs final update on the digest using hexadecimal string, - * then completes the digest computation - * @name doFinalHex - * @memberOf KJUR.crypto.Mac - * @function - * @param {String} hex hexadecimal string to final update - * @description - * @example - * md.digestHex('0f2abd') - */ - this.doFinalHex = function(hex) { - throw "digestHex(hex) not supported for this alg/prov: " + this.algProv; - }; - - if (params !== undefined) { - if (params['pass'] !== undefined) { - this.pass = params['pass']; - } - if (params['alg'] !== undefined) { - this.algName = params['alg']; - if (params['prov'] === undefined) - this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]; - this.setAlgAndProvider(this.algName, this.provName); - } - } -}; - -/** - * Signature class which is very similar to java.security.Signature class - * @name KJUR.crypto.Signature - * @class Signature class which is very similar to java.security.Signature class - * @param {Array} params parameters for constructor - * @property {String} state Current state of this signature object whether 'SIGN', 'VERIFY' or null - * @description - *
- * As for params of constructor's argument, it can be specify following attributes: - *
    - *
  • alg - signature algorithm name (ex. {MD5,SHA1,SHA224,SHA256,SHA384,SHA512,RIPEMD160}with{RSA,ECDSA,DSA})
  • - *
  • provider - currently 'cryptojs/jsrsa' only
  • - *
- *

SUPPORTED ALGORITHMS AND PROVIDERS

- * This Signature class supports following signature algorithm and provider names: - *
    - *
  • MD5withRSA - cryptojs/jsrsa
  • - *
  • SHA1withRSA - cryptojs/jsrsa
  • - *
  • SHA224withRSA - cryptojs/jsrsa
  • - *
  • SHA256withRSA - cryptojs/jsrsa
  • - *
  • SHA384withRSA - cryptojs/jsrsa
  • - *
  • SHA512withRSA - cryptojs/jsrsa
  • - *
  • RIPEMD160withRSA - cryptojs/jsrsa
  • - *
  • MD5withECDSA - cryptojs/jsrsa
  • - *
  • SHA1withECDSA - cryptojs/jsrsa
  • - *
  • SHA224withECDSA - cryptojs/jsrsa
  • - *
  • SHA256withECDSA - cryptojs/jsrsa
  • - *
  • SHA384withECDSA - cryptojs/jsrsa
  • - *
  • SHA512withECDSA - cryptojs/jsrsa
  • - *
  • RIPEMD160withECDSA - cryptojs/jsrsa
  • - *
  • MD5withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA1withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA224withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA256withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA384withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA512withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • RIPEMD160withRSAandMGF1 - cryptojs/jsrsa
  • - *
  • SHA1withDSA - cryptojs/jsrsa
  • - *
  • SHA224withDSA - cryptojs/jsrsa
  • - *
  • SHA256withDSA - cryptojs/jsrsa
  • - *
- * Here are supported elliptic cryptographic curve names and their aliases for ECDSA: - *
    - *
  • secp256k1
  • - *
  • secp256r1, NIST P-256, P-256, prime256v1
  • - *
  • secp384r1, NIST P-384, P-384
  • - *
- * NOTE1: DSA signing algorithm is also supported since crypto 1.1.5. - *

EXAMPLES

- * @example - * // RSA signature generation - * var sig = new KJUR.crypto.Signature({"alg": "SHA1withRSA"}); - * sig.init(prvKeyPEM); - * sig.updateString('aaa'); - * var hSigVal = sig.sign(); - * - * // DSA signature validation - * var sig2 = new KJUR.crypto.Signature({"alg": "SHA1withDSA"}); - * sig2.init(certPEM); - * sig.updateString('aaa'); - * var isValid = sig2.verify(hSigVal); - * - * // ECDSA signing - * var sig = new KJUR.crypto.Signature({'alg':'SHA1withECDSA'}); - * sig.init(prvKeyPEM); - * sig.updateString('aaa'); - * var sigValueHex = sig.sign(); - * - * // ECDSA verifying - * var sig2 = new KJUR.crypto.Signature({'alg':'SHA1withECDSA'}); - * sig.init(certPEM); - * sig.updateString('aaa'); - * var isValid = sig.verify(sigValueHex); - */ -KJUR.crypto.Signature = function(params) { - var prvKey = null; // RSAKey/KJUR.crypto.{ECDSA,DSA} object for signing - var pubKey = null; // RSAKey/KJUR.crypto.{ECDSA,DSA} object for verifying - - var md = null; // KJUR.crypto.MessageDigest object - var sig = null; - var algName = null; - var provName = null; - var algProvName = null; - var mdAlgName = null; - var pubkeyAlgName = null; // rsa,ecdsa,rsaandmgf1(=rsapss) - var state = null; - var pssSaltLen = -1; - var initParams = null; - - var sHashHex = null; // hex hash value for hex - var hDigestInfo = null; - var hPaddedDigestInfo = null; - var hSign = null; - - this._setAlgNames = function() { - if (this.algName.match(/^(.+)with(.+)$/)) { - this.mdAlgName = RegExp.$1.toLowerCase(); - this.pubkeyAlgName = RegExp.$2.toLowerCase(); - } - }; - - this._zeroPaddingOfSignature = function(hex, bitLength) { - var s = ""; - var nZero = bitLength / 4 - hex.length; - for (var i = 0; i < nZero; i++) { - s = s + "0"; - } - return s + hex; - }; - - /** - * set signature algorithm and provider - * @name setAlgAndProvider - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} alg signature algorithm name - * @param {String} prov provider name - * @description - * @example - * md.setAlgAndProvider('SHA1withRSA', 'cryptojs/jsrsa'); - */ - this.setAlgAndProvider = function(alg, prov) { - this._setAlgNames(); - if (prov != 'cryptojs/jsrsa') - throw "provider not supported: " + prov; - - if (':md5:sha1:sha224:sha256:sha384:sha512:ripemd160:'.indexOf(this.mdAlgName) != -1) { - try { - this.md = new KJUR.crypto.MessageDigest({'alg':this.mdAlgName}); - } catch (ex) { - throw "setAlgAndProvider hash alg set fail alg=" + - this.mdAlgName + "/" + ex; - } - - this.init = function(keyparam, pass) { - var keyObj = null; - try { - if (pass === undefined) { - keyObj = KEYUTIL.getKey(keyparam); - } else { - keyObj = KEYUTIL.getKey(keyparam, pass); - } - } catch (ex) { - throw "init failed:" + ex; - } - - if (keyObj.isPrivate === true) { - this.prvKey = keyObj; - this.state = "SIGN"; - } else if (keyObj.isPublic === true) { - this.pubKey = keyObj; - this.state = "VERIFY"; - } else { - throw "init failed.:" + keyObj; - } - }; - - this.initSign = function(params) { - if (typeof params['ecprvhex'] == 'string' && - typeof params['eccurvename'] == 'string') { - this.ecprvhex = params['ecprvhex']; - this.eccurvename = params['eccurvename']; - } else { - this.prvKey = params; - } - this.state = "SIGN"; - }; - - this.initVerifyByPublicKey = function(params) { - if (typeof params['ecpubhex'] == 'string' && - typeof params['eccurvename'] == 'string') { - this.ecpubhex = params['ecpubhex']; - this.eccurvename = params['eccurvename']; - } else if (params instanceof KJUR.crypto.ECDSA) { - this.pubKey = params; - } else if (params instanceof RSAKey) { - this.pubKey = params; - } - this.state = "VERIFY"; - }; - - this.initVerifyByCertificatePEM = function(certPEM) { - var x509 = new X509(); - x509.readCertPEM(certPEM); - this.pubKey = x509.subjectPublicKeyRSA; - this.state = "VERIFY"; - }; - - this.updateString = function(str) { - this.md.updateString(str); - }; - this.updateHex = function(hex) { - this.md.updateHex(hex); - }; - - this.sign = function() { - this.sHashHex = this.md.digest(); - if (typeof this.ecprvhex != "undefined" && - typeof this.eccurvename != "undefined") { - var ec = new KJUR.crypto.ECDSA({'curve': this.eccurvename}); - this.hSign = ec.signHex(this.sHashHex, this.ecprvhex); - } else if (this.pubkeyAlgName == "rsaandmgf1") { - this.hSign = this.prvKey.signWithMessageHashPSS(this.sHashHex, - this.mdAlgName, - this.pssSaltLen); - } else if (this.pubkeyAlgName == "rsa") { - this.hSign = this.prvKey.signWithMessageHash(this.sHashHex, - this.mdAlgName); - } else if (this.prvKey instanceof KJUR.crypto.ECDSA) { - this.hSign = this.prvKey.signWithMessageHash(this.sHashHex); - } else if (this.prvKey instanceof KJUR.crypto.DSA) { - this.hSign = this.prvKey.signWithMessageHash(this.sHashHex); - } else { - throw "Signature: unsupported public key alg: " + this.pubkeyAlgName; - } - return this.hSign; - }; - this.signString = function(str) { - this.updateString(str); - return this.sign(); - }; - this.signHex = function(hex) { - this.updateHex(hex); - return this.sign(); - }; - this.verify = function(hSigVal) { - this.sHashHex = this.md.digest(); - if (typeof this.ecpubhex != "undefined" && - typeof this.eccurvename != "undefined") { - var ec = new KJUR.crypto.ECDSA({curve: this.eccurvename}); - return ec.verifyHex(this.sHashHex, hSigVal, this.ecpubhex); - } else if (this.pubkeyAlgName == "rsaandmgf1") { - return this.pubKey.verifyWithMessageHashPSS(this.sHashHex, hSigVal, - this.mdAlgName, - this.pssSaltLen); - } else if (this.pubkeyAlgName == "rsa") { - return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal); - } else if (this.pubKey instanceof KJUR.crypto.ECDSA) { - return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal); - } else if (this.pubKey instanceof KJUR.crypto.DSA) { - return this.pubKey.verifyWithMessageHash(this.sHashHex, hSigVal); - } else { - throw "Signature: unsupported public key alg: " + this.pubkeyAlgName; - } - }; - } - }; - - /** - * Initialize this object for signing or verifying depends on key - * @name init - * @memberOf KJUR.crypto.Signature - * @function - * @param {Object} key specifying public or private key as plain/encrypted PKCS#5/8 PEM file, certificate PEM or {@link RSAKey}, {@link KJUR.crypto.DSA} or {@link KJUR.crypto.ECDSA} object - * @param {String} pass (OPTION) passcode for encrypted private key - * @since crypto 1.1.3 - * @description - * This method is very useful initialize method for Signature class since - * you just specify key then this method will automatically initialize it - * using {@link KEYUTIL.getKey} method. - * As for 'key', following argument type are supported: - *
signing
- *
    - *
  • PEM formatted PKCS#8 encrypted RSA/ECDSA private key concluding "BEGIN ENCRYPTED PRIVATE KEY"
  • - *
  • PEM formatted PKCS#5 encrypted RSA/DSA private key concluding "BEGIN RSA/DSA PRIVATE KEY" and ",ENCRYPTED"
  • - *
  • PEM formatted PKCS#8 plain RSA/ECDSA private key concluding "BEGIN PRIVATE KEY"
  • - *
  • PEM formatted PKCS#5 plain RSA/DSA private key concluding "BEGIN RSA/DSA PRIVATE KEY" without ",ENCRYPTED"
  • - *
  • RSAKey object of private key
  • - *
  • KJUR.crypto.ECDSA object of private key
  • - *
  • KJUR.crypto.DSA object of private key
  • - *
- *
verification
- *
    - *
  • PEM formatted PKCS#8 RSA/EC/DSA public key concluding "BEGIN PUBLIC KEY"
  • - *
  • PEM formatted X.509 certificate with RSA/EC/DSA public key concluding - * "BEGIN CERTIFICATE", "BEGIN X509 CERTIFICATE" or "BEGIN TRUSTED CERTIFICATE".
  • - *
  • RSAKey object of public key
  • - *
  • KJUR.crypto.ECDSA object of public key
  • - *
  • KJUR.crypto.DSA object of public key
  • - *
- * @example - * sig.init(sCertPEM) - */ - this.init = function(key, pass) { - throw "init(key, pass) not supported for this alg:prov=" + - this.algProvName; - }; - - /** - * Initialize this object for verifying with a public key - * @name initVerifyByPublicKey - * @memberOf KJUR.crypto.Signature - * @function - * @param {Object} param RSAKey object of public key or associative array for ECDSA - * @since 1.0.2 - * @deprecated from crypto 1.1.5. please use init() method instead. - * @description - * Public key information will be provided as 'param' parameter and the value will be - * following: - *
    - *
  • {@link RSAKey} object for RSA verification
  • - *
  • associative array for ECDSA verification - * (ex. {'ecpubhex': '041f..', 'eccurvename': 'secp256r1'}) - *
  • - *
- * @example - * sig.initVerifyByPublicKey(rsaPrvKey) - */ - this.initVerifyByPublicKey = function(rsaPubKey) { - throw "initVerifyByPublicKey(rsaPubKeyy) not supported for this alg:prov=" + - this.algProvName; - }; - - /** - * Initialize this object for verifying with a certficate - * @name initVerifyByCertificatePEM - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} certPEM PEM formatted string of certificate - * @since 1.0.2 - * @deprecated from crypto 1.1.5. please use init() method instead. - * @description - * @example - * sig.initVerifyByCertificatePEM(certPEM) - */ - this.initVerifyByCertificatePEM = function(certPEM) { - throw "initVerifyByCertificatePEM(certPEM) not supported for this alg:prov=" + - this.algProvName; - }; - - /** - * Initialize this object for signing - * @name initSign - * @memberOf KJUR.crypto.Signature - * @function - * @param {Object} param RSAKey object of public key or associative array for ECDSA - * @deprecated from crypto 1.1.5. please use init() method instead. - * @description - * Private key information will be provided as 'param' parameter and the value will be - * following: - *
    - *
  • {@link RSAKey} object for RSA signing
  • - *
  • associative array for ECDSA signing - * (ex. {'ecprvhex': '1d3f..', 'eccurvename': 'secp256r1'})
  • - *
- * @example - * sig.initSign(prvKey) - */ - this.initSign = function(prvKey) { - throw "initSign(prvKey) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * Updates the data to be signed or verified by a string - * @name updateString - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} str string to use for the update - * @description - * @example - * sig.updateString('aaa') - */ - this.updateString = function(str) { - throw "updateString(str) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * Updates the data to be signed or verified by a hexadecimal string - * @name updateHex - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} hex hexadecimal string to use for the update - * @description - * @example - * sig.updateHex('1f2f3f') - */ - this.updateHex = function(hex) { - throw "updateHex(hex) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * Returns the signature bytes of all data updates as a hexadecimal string - * @name sign - * @memberOf KJUR.crypto.Signature - * @function - * @return the signature bytes as a hexadecimal string - * @description - * @example - * var hSigValue = sig.sign() - */ - this.sign = function() { - throw "sign() not supported for this alg:prov=" + this.algProvName; - }; - - /** - * performs final update on the sign using string, then returns the signature bytes of all data updates as a hexadecimal string - * @name signString - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} str string to final update - * @return the signature bytes of a hexadecimal string - * @description - * @example - * var hSigValue = sig.signString('aaa') - */ - this.signString = function(str) { - throw "digestString(str) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * performs final update on the sign using hexadecimal string, then returns the signature bytes of all data updates as a hexadecimal string - * @name signHex - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} hex hexadecimal string to final update - * @return the signature bytes of a hexadecimal string - * @description - * @example - * var hSigValue = sig.signHex('1fdc33') - */ - this.signHex = function(hex) { - throw "digestHex(hex) not supported for this alg:prov=" + this.algProvName; - }; - - /** - * verifies the passed-in signature. - * @name verify - * @memberOf KJUR.crypto.Signature - * @function - * @param {String} str string to final update - * @return {Boolean} true if the signature was verified, otherwise false - * @description - * @example - * var isValid = sig.verify('1fbcefdca4823a7(snip)') - */ - this.verify = function(hSigVal) { - throw "verify(hSigVal) not supported for this alg:prov=" + this.algProvName; - }; - - this.initParams = params; - - if (params !== undefined) { - if (params['alg'] !== undefined) { - this.algName = params['alg']; - if (params['prov'] === undefined) { - this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName]; - } else { - this.provName = params['prov']; - } - this.algProvName = this.algName + ":" + this.provName; - this.setAlgAndProvider(this.algName, this.provName); - this._setAlgNames(); - } - - if (params['psssaltlen'] !== undefined) this.pssSaltLen = params['psssaltlen']; - - if (params['prvkeypem'] !== undefined) { - if (params['prvkeypas'] !== undefined) { - throw "both prvkeypem and prvkeypas parameters not supported"; - } else { - try { - var prvKey = new RSAKey(); - prvKey.readPrivateKeyFromPEMString(params['prvkeypem']); - this.initSign(prvKey); - } catch (ex) { - throw "fatal error to load pem private key: " + ex; - } - } - } - } -}; - -/** - * static object for cryptographic function utilities - * @name KJUR.crypto.OID - * @class static object for cryptography related OIDs - * @property {Array} oidhex2name key value of hexadecimal OID and its name - * (ex. '2a8648ce3d030107' and 'secp256r1') - * @since crypto 1.1.3 - * @description - */ - - -KJUR.crypto.OID = new function() { - this.oidhex2name = { - '2a864886f70d010101': 'rsaEncryption', - '2a8648ce3d0201': 'ecPublicKey', - '2a8648ce380401': 'dsa', - '2a8648ce3d030107': 'secp256r1', - '2b8104001f': 'secp192k1', - '2b81040021': 'secp224r1', - '2b8104000a': 'secp256k1', - '2b81040023': 'secp521r1', - '2b81040022': 'secp384r1', - '2a8648ce380403': 'SHA1withDSA', // 1.2.840.10040.4.3 - '608648016503040301': 'SHA224withDSA', // 2.16.840.1.101.3.4.3.1 - '608648016503040302': 'SHA256withDSA', // 2.16.840.1.101.3.4.3.2 - }; -}; - -/*! base64x-1.1.3 (c) 2012-2014 Kenji Urushima | kjur.github.com/jsjws/license - */ -/* - * base64x.js - Base64url and supplementary functions for Tom Wu's base64.js library - * - * version: 1.1.3 (2014 May 25) - * - * Copyright (c) 2012-2014 Kenji Urushima (kenji.urushima@gmail.com) - * - * This software is licensed under the terms of the MIT License. - * http://kjur.github.com/jsjws/license/ - * - * The above copyright and license notice shall be - * included in all copies or substantial portions of the Software. - * - * DEPENDS ON: - * - base64.js - Tom Wu's Base64 library - */ - -/** - * Base64URL and supplementary functions for Tom Wu's base64.js library.
- * This class is just provide information about global functions - * defined in 'base64x.js'. The 'base64x.js' script file provides - * global functions for converting following data each other. - *
    - *
  • (ASCII) String
  • - *
  • UTF8 String including CJK, Latin and other characters
  • - *
  • byte array
  • - *
  • hexadecimal encoded String
  • - *
  • Full URIComponent encoded String (such like "%69%94")
  • - *
  • Base64 encoded String
  • - *
  • Base64URL encoded String
  • - *
- * All functions in 'base64x.js' are defined in {@link _global_} and not - * in this class. - * - * @class Base64URL and supplementary functions for Tom Wu's base64.js library - * @author Kenji Urushima - * @version 1.1 (07 May 2012) - * @requires base64.js - * @see 'jwjws'(JWS JavaScript Library) home page http://kjur.github.com/jsjws/ - * @see 'jwrsasign'(RSA Sign JavaScript Library) home page http://kjur.github.com/jsrsasign/ - */ -function Base64x() { -} - -// ==== string / byte array ================================ -/** - * convert a string to an array of character codes - * @param {String} s - * @return {Array of Numbers} - */ -function stoBA(s) { - var a = new Array(); - for (var i = 0; i < s.length; i++) { - a[i] = s.charCodeAt(i); - } - return a; -} - -/** - * convert an array of character codes to a string - * @param {Array of Numbers} a array of character codes - * @return {String} s - */ -function BAtos(a) { - var s = ""; - for (var i = 0; i < a.length; i++) { - s = s + String.fromCharCode(a[i]); - } - return s; -} - -// ==== byte array / hex ================================ -/** - * convert an array of bytes(Number) to hexadecimal string.
- * @param {Array of Numbers} a array of bytes - * @return {String} hexadecimal string - */ -function BAtohex(a) { - var s = ""; - for (var i = 0; i < a.length; i++) { - var hex1 = a[i].toString(16); - if (hex1.length == 1) hex1 = "0" + hex1; - s = s + hex1; - } - return s; -} - -// ==== string / hex ================================ -/** - * convert a ASCII string to a hexadecimal string of ASCII codes.
- * NOTE: This can't be used for non ASCII characters. - * @param {s} s ASCII string - * @return {String} hexadecimal string - */ -function stohex(s) { - return BAtohex(stoBA(s)); -} - -// ==== string / base64 ================================ -/** - * convert a ASCII string to a Base64 encoded string.
- * NOTE: This can't be used for non ASCII characters. - * @param {s} s ASCII string - * @return {String} Base64 encoded string - */ -function stob64(s) { - return hex2b64(stohex(s)); -} - -// ==== string / base64url ================================ -/** - * convert a ASCII string to a Base64URL encoded string.
- * NOTE: This can't be used for non ASCII characters. - * @param {s} s ASCII string - * @return {String} Base64URL encoded string - */ -function stob64u(s) { - return b64tob64u(hex2b64(stohex(s))); -} - -/** - * convert a Base64URL encoded string to a ASCII string.
- * NOTE: This can't be used for Base64URL encoded non ASCII characters. - * @param {s} s Base64URL encoded string - * @return {String} ASCII string - */ -function b64utos(s) { - return BAtos(b64toBA(b64utob64(s))); -} - -// ==== base64 / base64url ================================ -/** - * convert a Base64 encoded string to a Base64URL encoded string.
- * Example: "ab+c3f/==" → "ab-c3f_" - * @param {String} s Base64 encoded string - * @return {String} Base64URL encoded string - */ -function b64tob64u(s) { - s = s.replace(/\=/g, ""); - s = s.replace(/\+/g, "-"); - s = s.replace(/\//g, "_"); - return s; -} - -/** - * convert a Base64URL encoded string to a Base64 encoded string.
- * Example: "ab-c3f_" → "ab+c3f/==" - * @param {String} s Base64URL encoded string - * @return {String} Base64 encoded string - */ -function b64utob64(s) { - if (s.length % 4 == 2) s = s + "=="; - else if (s.length % 4 == 3) s = s + "="; - s = s.replace(/-/g, "+"); - s = s.replace(/_/g, "/"); - return s; -} - -// ==== hex / base64url ================================ -/** - * convert a hexadecimal string to a Base64URL encoded string.
- * @param {String} s hexadecimal string - * @return {String} Base64URL encoded string - */ -function hextob64u(s) { - return b64tob64u(hex2b64(s)); -} - -/** - * convert a Base64URL encoded string to a hexadecimal string.
- * @param {String} s Base64URL encoded string - * @return {String} hexadecimal string - */ -function b64utohex(s) { - return b64tohex(b64utob64(s)); -} - -var utf8tob64u, b64utoutf8; - -if (typeof Buffer === 'function') -{ - utf8tob64u = function (s) - { - return b64tob64u(new Buffer(s, 'utf8').toString('base64')); - }; - - b64utoutf8 = function (s) - { - return new Buffer(b64utob64(s), 'base64').toString('utf8'); - }; -} -else -{ -// ==== utf8 / base64url ================================ -/** - * convert a UTF-8 encoded string including CJK or Latin to a Base64URL encoded string.
- * @param {String} s UTF-8 encoded string - * @return {String} Base64URL encoded string - * @since 1.1 - */ - utf8tob64u = function (s) - { - return hextob64u(uricmptohex(encodeURIComponentAll(s))); - }; - -/** - * convert a Base64URL encoded string to a UTF-8 encoded string including CJK or Latin.
- * @param {String} s Base64URL encoded string - * @return {String} UTF-8 encoded string - * @since 1.1 - */ - b64utoutf8 = function (s) - { - return decodeURIComponent(hextouricmp(b64utohex(s))); - }; -} - -// ==== utf8 / base64url ================================ -/** - * convert a UTF-8 encoded string including CJK or Latin to a Base64 encoded string.
- * @param {String} s UTF-8 encoded string - * @return {String} Base64 encoded string - * @since 1.1.1 - */ -function utf8tob64(s) { - return hex2b64(uricmptohex(encodeURIComponentAll(s))); -} - -/** - * convert a Base64 encoded string to a UTF-8 encoded string including CJK or Latin.
- * @param {String} s Base64 encoded string - * @return {String} UTF-8 encoded string - * @since 1.1.1 - */ -function b64toutf8(s) { - return decodeURIComponent(hextouricmp(b64tohex(s))); -} - -// ==== utf8 / hex ================================ -/** - * convert a UTF-8 encoded string including CJK or Latin to a hexadecimal encoded string.
- * @param {String} s UTF-8 encoded string - * @return {String} hexadecimal encoded string - * @since 1.1.1 - */ -function utf8tohex(s) { - return uricmptohex(encodeURIComponentAll(s)); -} - -/** - * convert a hexadecimal encoded string to a UTF-8 encoded string including CJK or Latin.
- * Note that when input is improper hexadecimal string as UTF-8 string, this function returns - * 'null'. - * @param {String} s hexadecimal encoded string - * @return {String} UTF-8 encoded string or null - * @since 1.1.1 - */ -function hextoutf8(s) { - return decodeURIComponent(hextouricmp(s)); -} - -/** - * convert a hexadecimal encoded string to raw string including non printable characters.
- * @param {String} s hexadecimal encoded string - * @return {String} raw string - * @since 1.1.2 - * @example - * hextorstr("610061") → "a\x00a" - */ -function hextorstr(sHex) { - var s = ""; - for (var i = 0; i < sHex.length - 1; i += 2) { - s += String.fromCharCode(parseInt(sHex.substr(i, 2), 16)); - } - return s; -} - -/** - * convert a raw string including non printable characters to hexadecimal encoded string.
- * @param {String} s raw string - * @return {String} hexadecimal encoded string - * @since 1.1.2 - * @example - * rstrtohex("a\x00a") → "610061" - */ -function rstrtohex(s) { - var result = ""; - for (var i = 0; i < s.length; i++) { - result += ("0" + s.charCodeAt(i).toString(16)).slice(-2); - } - return result; -} - -// ==== hex / b64nl ======================================= - -/* - * since base64x 1.1.3 - */ -function hextob64(s) { - return hex2b64(s); -} - -/* - * since base64x 1.1.3 - */ -function hextob64nl(s) { - var b64 = hextob64(s); - var b64nl = b64.replace(/(.{64})/g, "$1\r\n"); - b64nl = b64nl.replace(/\r\n$/, ''); - return b64nl; -} - -/* - * since base64x 1.1.3 - */ -function b64nltohex(s) { - var b64 = s.replace(/[^0-9A-Za-z\/+=]*/g, ''); - var hex = b64tohex(b64); - return hex; -} - -// ==== URIComponent / hex ================================ -/** - * convert a URLComponent string such like "%67%68" to a hexadecimal string.
- * @param {String} s URIComponent string such like "%67%68" - * @return {String} hexadecimal string - * @since 1.1 - */ -function uricmptohex(s) { - return s.replace(/%/g, ""); -} - -/** - * convert a hexadecimal string to a URLComponent string such like "%67%68".
- * @param {String} s hexadecimal string - * @return {String} URIComponent string such like "%67%68" - * @since 1.1 - */ -function hextouricmp(s) { - return s.replace(/(..)/g, "%$1"); -} - -// ==== URIComponent ================================ -/** - * convert UTFa hexadecimal string to a URLComponent string such like "%67%68".
- * Note that these "0-9A-Za-z!'()*-._~" characters will not - * converted to "%xx" format by builtin 'encodeURIComponent()' function. - * However this 'encodeURIComponentAll()' function will convert - * all of characters into "%xx" format. - * @param {String} s hexadecimal string - * @return {String} URIComponent string such like "%67%68" - * @since 1.1 - */ -function encodeURIComponentAll(u8) { - var s = encodeURIComponent(u8); - var s2 = ""; - for (var i = 0; i < s.length; i++) { - if (s[i] == "%") { - s2 = s2 + s.substr(i, 3); - i = i + 2; - } else { - s2 = s2 + "%" + stohex(s[i]); - } - } - return s2; -} - -// ==== new lines ================================ -/** - * convert all DOS new line("\r\n") to UNIX new line("\n") in - * a String "s". - * @param {String} s string - * @return {String} converted string - */ -function newline_toUnix(s) { - s = s.replace(/\r\n/mg, "\n"); - return s; -} - -/** - * convert all UNIX new line("\r\n") to DOS new line("\n") in - * a String "s". - * @param {String} s string - * @return {String} converted string - */ -function newline_toDos(s) { - s = s.replace(/\r\n/mg, "\n"); - s = s.replace(/\n/mg, "\r\n"); - return s; -} diff --git a/oidc-client.js b/oidc-client.js deleted file mode 100644 index 7f6d9e67..00000000 --- a/oidc-client.js +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright 2015 Dominick Baier, Brock Allen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -function log() { - //var param = [].join.call(arguments); - //console.log(param); -} - -function copy(obj, target) { - target = target || {}; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - target[key] = obj[key]; - } - } - return target; -} - -function rand() { - return ((Date.now() + Math.random()) * Math.random()).toString().replace(".", ""); -} - -function resolve(param) { - return _promiseFactory.resolve(param); -} - -function error(message) { - return _promiseFactory.reject(Error(message)); -} - -function parseOidcResult(queryString) { - log("parseOidcResult"); - - queryString = queryString || location.hash; - - var idx = queryString.lastIndexOf("#"); - if (idx >= 0) { - queryString = queryString.substr(idx + 1); - } - - var params = {}, - regex = /([^&=]+)=([^&]*)/g, - m; - - var counter = 0; - while (m = regex.exec(queryString)) { - params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); - if (counter++ > 50) { - return { - error: "Response exceeded expected number of parameters" - }; - } - } - - for (var prop in params) { - return params; - } -} - -function getJson(url, token) { - log("getJson", url); - - var config = {}; - - if (token) { - config.headers = {"Authorization": "Bearer " + token}; - } - - return _httpRequest.getJSON(url, config); -} - -function OidcClient(settings) { - this._settings = settings || {}; - - if (!this._settings.request_state_key) { - this._settings.request_state_key = "OidcClient.request_state"; - } - - if (!this._settings.request_state_store) { - this._settings.request_state_store = window.localStorage; - } - - if (typeof this._settings.load_user_profile === 'undefined') { - this._settings.load_user_profile = true; - } - - if (typeof this._settings.filter_protocol_claims === 'undefined') { - this._settings.filter_protocol_claims = true; - } - - if (this._settings.authority && this._settings.authority.indexOf('.well-known/openid-configuration') < 0) { - if (this._settings.authority[this._settings.authority.length - 1] !== '/') { - this._settings.authority += '/'; - } - this._settings.authority += '.well-known/openid-configuration'; - } - - if (!this._settings.response_type) { - this._settings.response_type = "id_token token"; - } - - Object.defineProperty(this, "isOidc", { - get: function () { - if (this._settings.response_type) { - var result = this._settings.response_type.split(/\s+/g).filter(function (item) { - return item === "id_token"; - }); - return !!(result[0]); - } - return false; - } - }); - - Object.defineProperty(this, "isOAuth", { - get: function () { - if (this._settings.response_type) { - var result = this._settings.response_type.split(/\s+/g).filter(function (item) { - return item === "token"; - }); - return !!(result[0]); - } - return false; - } - }); -} - -OidcClient.parseOidcResult = parseOidcResult; - -OidcClient.prototype.loadMetadataAsync = function () { - log("OidcClient.loadMetadataAsync"); - - var settings = this._settings; - - if (settings.metadata) { - return resolve(settings.metadata); - } - - if (!settings.authority) { - return error("No authority configured"); - } - - return getJson(settings.authority) - .then(function (metadata) { - settings.metadata = metadata; - return metadata; - }, function (err) { - return error("Failed to load metadata (" + err && err.message + ")"); - }); -}; - -OidcClient.prototype.loadX509SigningKeyAsync = function () { - log("OidcClient.loadX509SigningKeyAsync"); - - var settings = this._settings; - - function getKeyAsync(jwks) { - if (!jwks.keys || !jwks.keys.length) { - return error("Signing keys empty"); - } - - var key = jwks.keys[0]; - if (key.kty !== "RSA") { - return error("Signing key not RSA"); - } - - if (!key.x5c || !key.x5c.length) { - return error("RSA keys empty"); - } - - return resolve(key.x5c[0]); - } - - if (settings.jwks) { - return getKeyAsync(settings.jwks); - } - - return this.loadMetadataAsync().then(function (metadata) { - if (!metadata.jwks_uri) { - return error("Metadata does not contain jwks_uri"); - } - - return getJson(metadata.jwks_uri).then(function (jwks) { - settings.jwks = jwks; - return getKeyAsync(jwks); - }, function (err) { - return error("Failed to load signing keys (" + err && err.message + ")"); - }); - }); -}; - -OidcClient.prototype.loadUserProfile = function (access_token) { - log("OidcClient.loadUserProfile"); - - return this.loadMetadataAsync().then(function (metadata) { - - if (!metadata.userinfo_endpoint) { - return error("Metadata does not contain userinfo_endpoint"); - } - - return getJson(metadata.userinfo_endpoint, access_token); - }); -} - -OidcClient.prototype.loadAuthorizationEndpoint = function () { - log("OidcClient.loadAuthorizationEndpoint"); - - if (this._settings.authorization_endpoint) { - return resolve(this._settings.authorization_endpoint); - } - - if (!this._settings.authority) { - return error("No authorization_endpoint configured"); - } - - return this.loadMetadataAsync().then(function (metadata) { - if (!metadata.authorization_endpoint) { - return error("Metadata does not contain authorization_endpoint"); - } - - return metadata.authorization_endpoint; - }); -}; - -OidcClient.prototype.createTokenRequestAsync = function () { - log("OidcClient.createTokenRequestAsync"); - - var client = this; - var settings = client._settings; - - return client.loadAuthorizationEndpoint().then(function (authorization_endpoint) { - - var state = rand(); - var url = authorization_endpoint + "?state=" + encodeURIComponent(state); - - if (client.isOidc) { - var nonce = rand(); - url += "&nonce=" + encodeURIComponent(nonce); - } - - var required = ["client_id", "redirect_uri", "response_type", "scope"]; - required.forEach(function (key) { - var value = settings[key]; - if (value) { - url += "&" + key + "=" + encodeURIComponent(value); - } - }); - - var optional = ["prompt", "display", "max_age", "ui_locales", "id_token_hint", "login_hint", "acr_values"]; - optional.forEach(function (key) { - var value = settings[key]; - if (value) { - url += "&" + key + "=" + encodeURIComponent(value); - } - }); - - var request_state = { - oidc: client.isOidc, - oauth: client.isOAuth, - state: state - }; - - if (nonce) { - request_state["nonce"] = nonce; - } - - settings.request_state_store.setItem(settings.request_state_key, JSON.stringify(request_state)); - - return { - request_state: request_state, - url: url - }; - }); -} - -OidcClient.prototype.createLogoutRequestAsync = function (id_token_hint) { - log("OidcClient.createLogoutRequestAsync"); - - var settings = this._settings; - return this.loadMetadataAsync().then(function (metadata) { - if (!metadata.end_session_endpoint) { - return error("No end_session_endpoint in metadata"); - } - - var url = metadata.end_session_endpoint; - if (id_token_hint && settings.post_logout_redirect_uri) { - url += "?post_logout_redirect_uri=" + encodeURIComponent(settings.post_logout_redirect_uri); - url += "&id_token_hint=" + encodeURIComponent(id_token_hint); - } - return url; - }); -} - -OidcClient.prototype.validateIdTokenAsync = function (id_token, nonce, access_token) { - log("OidcClient.validateIdTokenAsync"); - - var client = this; - var settings = client._settings; - - return client.loadX509SigningKeyAsync().then(function (cert) { - - var jws = new KJUR.jws.JWS(); - if (jws.verifyJWSByPemX509Cert(id_token, cert)) { - var id_token_contents = JSON.parse(jws.parsedJWS.payloadS); - - if (nonce !== id_token_contents.nonce) { - return error("Invalid nonce"); - } - - return client.loadMetadataAsync().then(function (metadata) { - - if (id_token_contents.iss !== metadata.issuer) { - return error("Invalid issuer"); - } - - if (id_token_contents.aud !== settings.client_id) { - return error("Invalid audience"); - } - - var now = parseInt(Date.now() / 1000); - - // accept tokens issues up to 5 mins ago - var diff = now - id_token_contents.iat; - if (diff > (5 * 60)) { - return error("Token issued too long ago"); - } - - if (id_token_contents.exp < now) { - return error("Token expired"); - } - - if (access_token && settings.load_user_profile) { - // if we have an access token, then call user info endpoint - return client.loadUserProfile(access_token, id_token_contents).then(function (profile) { - return copy(profile, id_token_contents); - }); - } - else { - // no access token, so we have all our claims - return id_token_contents; - } - - }); - } - else { - return error("JWT failed to validate"); - } - - }); - -}; - -OidcClient.prototype.validateAccessTokenAsync = function (id_token_contents, access_token) { - log("OidcClient.validateAccessTokenAsync"); - - if (!id_token_contents.at_hash) { - return error("No at_hash in id_token"); - } - - var hash = KJUR.crypto.Util.sha256(access_token); - var left = hash.substr(0, hash.length / 2); - var left_b64u = hextob64u(left); - - if (left_b64u !== id_token_contents.at_hash) { - return error("at_hash failed to validate"); - } - - return resolve(); -}; - -OidcClient.prototype.validateIdTokenAndAccessTokenAsync = function (id_token, nonce, access_token) { - log("OidcClient.validateIdTokenAndAccessTokenAsync"); - - var client = this; - - return client.validateIdTokenAsync(id_token, nonce, access_token).then(function (id_token_contents) { - - return client.validateAccessTokenAsync(id_token_contents, access_token).then(function () { - - return id_token_contents; - - }); - - }); -} - -OidcClient.prototype.processResponseAsync = function (queryString) { - log("OidcClient.processResponseAsync"); - - var client = this; - var settings = client._settings; - - var request_state = settings.request_state_store.getItem(settings.request_state_key); - settings.request_state_store.removeItem(settings.request_state_key); - - if (!request_state) { - return error("No request state loaded"); - } - - request_state = JSON.parse(request_state); - if (!request_state) { - return error("No request state loaded"); - } - - if (!request_state.state) { - return error("No state loaded"); - } - - var result = parseOidcResult(queryString); - if (!result) { - return error("No OIDC response"); - } - - if (result.error) { - return error(result.error); - } - - if (result.state !== request_state.state) { - return error("Invalid state"); - } - - if (request_state.oidc) { - if (!result.id_token) { - return error("No identity token"); - } - - if (!request_state.nonce) { - return error("No nonce loaded"); - } - } - - if (request_state.oauth) { - if (!result.access_token) { - return error("No access token"); - } - - if (!result.token_type || result.token_type.toLowerCase() !== "bearer") { - return error("Invalid token type"); - } - - if (!result.expires_in) { - return error("No token expiration"); - } - } - - var promise = resolve(); - if (request_state.oidc && request_state.oauth) { - promise = client.validateIdTokenAndAccessTokenAsync(result.id_token, request_state.nonce, result.access_token); - } - else if (request_state.oidc) { - promise = client.validateIdTokenAsync(result.id_token, request_state.nonce); - } - - return promise.then(function (profile) { - if (profile && settings.filter_protocol_claims) { - var remove = ["nonce", "at_hash", "iat", "nbf", "exp", "aud", "iss"]; - remove.forEach(function (key) { - delete profile[key]; - }); - } - - return { - profile: profile, - id_token: result.id_token, - access_token: result.access_token, - expires_in: result.expires_in, - scope: result.scope, - session_state : result.session_state - }; - }); -} diff --git a/package.json b/package.json index 514ecacd..129f988e 100644 --- a/package.json +++ b/package.json @@ -1,27 +1,30 @@ { - "name": "oidc-client", - "version": "0.3.3", - "description": "OpenID Connect (OIDC) client library", - "main": "oidc-client.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "https://github.com/IdentityModel/oidc-client.git" - }, - "author": "", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/IdentityModel/oidc-client/issues" - }, - "homepage": "https://github.com/IdentityModel/oidc-client", - "devDependencies": { - "bower": "^1.4.0", - "del": "^1.1.1", - "gulp": "^3.8.11", - "gulp-concat": "^2.5.2", - "gulp-rename": "^1.2.0", - "gulp-uglify": "^1.1.0" - } -} + "name": "oidc-client", + "version": "1.0.0", + "description": "OpenID Connect (OIDC) client library", + "main": "src/index.js", + "scripts": { + "build": "webpack", + "test": "mocha --compilers js:babel-register test/*.spec.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/IdentityModel/oidc-client.git" + }, + "author": "", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/IdentityModel/oidc-client/issues" + }, + "homepage": "https://github.com/IdentityModel/oidc-client", + "devDependencies": { + "babel-core": "^6.7.2", + "babel-loader": "^6.2.4", + "babel-plugin-add-module-exports": "^0.1.2", + "babel-preset-es2015": "^6.6.0", + "babel-register": "^6.7.2", + "mocha": "^2.4.5", + "chai": "^3.5.0", + "webpack": "^1.12.14" + } +} \ No newline at end of file diff --git a/sample/vs/.vs/config/applicationhost.config b/sample/vs/.vs/config/applicationhost.config deleted file mode 100644 index 7524ed39..00000000 --- a/sample/vs/.vs/config/applicationhost.config +++ /dev/null @@ -1,1046 +0,0 @@ - - - - - - - - -
-
-
-
-
-
-
-
- - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
-
-
-
- -
-
-
- -
-
- -
-
- -
-
-
- - -
-
-
-
-
-
- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sample/vs/Sample.sln b/sample/vs/Sample.sln deleted file mode 100644 index 8f88d2fe..00000000 --- a/sample/vs/Sample.sln +++ /dev/null @@ -1,27 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample", "Sample\Sample.csproj", "{E88CEDD3-30F8-4883-B450-57C2B6054945}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8C7D9D8D-9506-4738-9288-C040D631D8B4}" - ProjectSection(SolutionItems) = preProject - ..\..\dist\oidc-client.js = ..\..\dist\oidc-client.js - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E88CEDD3-30F8-4883-B450-57C2B6054945}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E88CEDD3-30F8-4883-B450-57C2B6054945}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E88CEDD3-30F8-4883-B450-57C2B6054945}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E88CEDD3-30F8-4883-B450-57C2B6054945}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/sample/vs/Sample/Properties/AssemblyInfo.cs b/sample/vs/Sample/Properties/AssemblyInfo.cs deleted file mode 100644 index 2890ad09..00000000 --- a/sample/vs/Sample/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Sample")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9e91b60e-27ee-4da7-ab1d-83e6ad6c2804")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sample/vs/Sample/Sample.csproj b/sample/vs/Sample/Sample.csproj deleted file mode 100644 index 5e7e354e..00000000 --- a/sample/vs/Sample/Sample.csproj +++ /dev/null @@ -1,112 +0,0 @@ - - - - - Debug - AnyCPU - - - 2.0 - {E88CEDD3-30F8-4883-B450-57C2B6054945} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - Sample - Sample - v4.5 - true - - - - - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - Web.config - - - Web.config - - - - - - - - - - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - True - True - 43942 - / - http://localhost:21575 - False - False - - - False - - - - - - \ No newline at end of file diff --git a/sample/vs/Sample/Web.Debug.config b/sample/vs/Sample/Web.Debug.config deleted file mode 100644 index 2e302f9f..00000000 --- a/sample/vs/Sample/Web.Debug.config +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/sample/vs/Sample/Web.Release.config b/sample/vs/Sample/Web.Release.config deleted file mode 100644 index c3584446..00000000 --- a/sample/vs/Sample/Web.Release.config +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/sample/vs/Sample/Web.config b/sample/vs/Sample/Web.config deleted file mode 100644 index 52c09723..00000000 --- a/sample/vs/Sample/Web.config +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sample/vs/Sample/index.html b/sample/vs/Sample/index.html deleted file mode 100644 index 5944de89..00000000 --- a/sample/vs/Sample/index.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - -
- - -

-    
-    
-    
-
-
diff --git a/sample/vs/Sample/jquery-2.1.0.min.js b/sample/vs/Sample/jquery-2.1.0.min.js
deleted file mode 100644
index cbe6abe5..00000000
--- a/sample/vs/Sample/jquery-2.1.0.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
-!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m=a.document,n="2.1.0",o=function(a,b){return new o.fn.init(a,b)},p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};o.fn=o.prototype={jquery:n,constructor:o,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=o.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return o.each(this,a,b)},map:function(a){return this.pushStack(o.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},o.extend=o.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||o.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(o.isPlainObject(d)||(e=o.isArray(d)))?(e?(e=!1,f=c&&o.isArray(c)?c:[]):f=c&&o.isPlainObject(c)?c:{},g[b]=o.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},o.extend({expando:"jQuery"+(n+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===o.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isPlainObject:function(a){if("object"!==o.type(a)||a.nodeType||o.isWindow(a))return!1;try{if(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=o.trim(a),a&&(1===a.indexOf("use strict")?(b=m.createElement("script"),b.text=a,m.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":k.call(a)},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?o.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),o.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||o.guid++,f):void 0},now:Date.now,support:l}),o.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=o.type(a);return"function"===c||o.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);o.find=t,o.expr=t.selectors,o.expr[":"]=o.expr.pseudos,o.unique=t.uniqueSort,o.text=t.getText,o.isXMLDoc=t.isXML,o.contains=t.contains;var u=o.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(o.isFunction(b))return o.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return o.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return o.filter(b,a,c);b=o.filter(b,a)}return o.grep(a,function(a){return g.call(b,a)>=0!==c})}o.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?o.find.matchesSelector(d,a)?[d]:[]:o.find.matches(a,o.grep(b,function(a){return 1===a.nodeType}))},o.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(o(a).filter(function(){for(b=0;c>b;b++)if(o.contains(e[b],this))return!0}));for(b=0;c>b;b++)o.find(a,e[b],d);return d=this.pushStack(c>1?o.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?o(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=o.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof o?b[0]:b,o.merge(this,o.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:m,!0)),v.test(c[1])&&o.isPlainObject(b))for(c in b)o.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=m.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=m,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):o.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(o):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),o.makeArray(a,this))};A.prototype=o.fn,y=o(m);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};o.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&o(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),o.fn.extend({has:function(a){var b=o(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(o.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?o(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&o.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?o.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(o(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(o.unique(o.merge(this.get(),o(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}o.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return o.dir(a,"parentNode")},parentsUntil:function(a,b,c){return o.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return o.dir(a,"nextSibling")},prevAll:function(a){return o.dir(a,"previousSibling")},nextUntil:function(a,b,c){return o.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return o.dir(a,"previousSibling",c)},siblings:function(a){return o.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return o.sibling(a.firstChild)},contents:function(a){return a.contentDocument||o.merge([],a.childNodes)}},function(a,b){o.fn[a]=function(c,d){var e=o.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=o.filter(d,e)),this.length>1&&(C[a]||o.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return o.each(a.match(E)||[],function(a,c){b[c]=!0}),b}o.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):o.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){o.each(b,function(b,c){var d=o.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&o.each(arguments,function(a,b){var c;while((c=o.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?o.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},o.extend({Deferred:function(a){var b=[["resolve","done",o.Callbacks("once memory"),"resolved"],["reject","fail",o.Callbacks("once memory"),"rejected"],["notify","progress",o.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return o.Deferred(function(c){o.each(b,function(b,f){var g=o.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&o.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?o.extend(a,d):d}},e={};return d.pipe=d.then,o.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&o.isFunction(a.promise)?e:0,g=1===f?a:o.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&o.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;o.fn.ready=function(a){return o.ready.promise().done(a),this},o.extend({isReady:!1,readyWait:1,holdReady:function(a){a?o.readyWait++:o.ready(!0)},ready:function(a){(a===!0?--o.readyWait:o.isReady)||(o.isReady=!0,a!==!0&&--o.readyWait>0||(H.resolveWith(m,[o]),o.fn.trigger&&o(m).trigger("ready").off("ready")))}});function I(){m.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),o.ready()}o.ready.promise=function(b){return H||(H=o.Deferred(),"complete"===m.readyState?setTimeout(o.ready):(m.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},o.ready.promise();var J=o.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===o.type(c)){e=!0;for(h in c)o.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,o.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(o(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};o.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=o.expando+Math.random()}K.uid=1,K.accepts=o.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,o.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(o.isEmptyObject(f))o.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,o.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{o.isArray(b)?d=b.concat(b.map(o.camelCase)):(e=o.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!o.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?o.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}o.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),o.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length; -while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=o.camelCase(d.slice(5)),P(f,d,e[d]));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=o.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),o.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||o.isArray(c)?d=L.access(a,b,o.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=o.queue(a,b),d=c.length,e=c.shift(),f=o._queueHooks(a,b),g=function(){o.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:o.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),o.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";l.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return m.activeElement}catch(a){}}o.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=o.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof o!==U&&o.event.triggered!==b.type?o.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n&&(l=o.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=o.event.special[n]||{},k=o.extend({type:n,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&o.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),o.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n){l=o.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||o.removeEvent(a,n,r.handle),delete i[n])}else for(n in i)o.event.remove(a,n+b[j],c,d,!0);o.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,p=[d||m],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||m,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+o.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[o.expando]?b:new o.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:o.makeArray(c,[b]),n=o.event.special[q]||{},e||!n.trigger||n.trigger.apply(d,c)!==!1)){if(!e&&!n.noBubble&&!o.isWindow(d)){for(i=n.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||m)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:n.bindType||q,l=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),l&&l.apply(g,c),l=k&&g[k],l&&l.apply&&o.acceptData(g)&&(b.result=l.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||n._default&&n._default.apply(p.pop(),c)!==!1||!o.acceptData(d)||k&&o.isFunction(d[q])&&!o.isWindow(d)&&(h=d[k],h&&(d[k]=null),o.event.triggered=q,d[q](),o.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=o.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=o.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=o.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((o.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?o(e,this).index(i)>=0:o.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return o.nodeName(a,"table")&&o.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)o.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=o.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&o.nodeName(a,b)?o.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}o.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=o.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||o.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,n=a.length;n>m;m++)if(e=a[m],e||0===e)if("object"===o.type(e))o.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;o.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===o.inArray(e,d))&&(i=o.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f,g,h=o.event.special,i=0;void 0!==(c=a[i]);i++){if(o.acceptData(c)&&(f=c[L.expando],f&&(b=L.cache[f]))){if(d=Object.keys(b.events||{}),d.length)for(g=0;void 0!==(e=d[g]);g++)h[e]?o.event.remove(c,e):o.removeEvent(c,e,b.handle);L.cache[f]&&delete L.cache[f]}delete M.cache[c[M.expando]]}}}),o.fn.extend({text:function(a){return J(this,function(a){return void 0===a?o.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?o.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||o.cleanData(ob(c)),c.parentNode&&(b&&o.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(o.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return o.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(o.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,o.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,n=k-1,p=a[0],q=o.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(c=o.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=o.map(ob(c,"script"),kb),g=f.length;k>j;j++)h=c,j!==n&&(h=o.clone(h,!0,!0),g&&o.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,o.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&o.contains(i,h)&&(h.src?o._evalUrl&&o._evalUrl(h.src):o.globalEval(h.textContent.replace(hb,"")))}return this}}),o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){o.fn[a]=function(a){for(var c,d=[],e=o(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),o(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d=o(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:o.css(d[0],"display");return d.detach(),e}function tb(a){var b=m,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||o("