core.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. ;(function (root, factory) {
  2. if (typeof exports === "object") {
  3. // CommonJS
  4. module.exports = exports = factory();
  5. }
  6. else if (typeof define === "function" && define.amd) {
  7. // AMD
  8. define([], factory);
  9. }
  10. else {
  11. // Global (browser)
  12. root.CryptoJS = factory();
  13. }
  14. }(this, function () {
  15. /**
  16. * CryptoJS core components.
  17. */
  18. var CryptoJS = CryptoJS || (function (Math, undefined) {
  19. /*
  20. * Local polyfil of Object.create
  21. */
  22. var create = Object.create || (function () {
  23. function F() {};
  24. return function (obj) {
  25. var subtype;
  26. F.prototype = obj;
  27. subtype = new F();
  28. F.prototype = null;
  29. return subtype;
  30. };
  31. }())
  32. /**
  33. * CryptoJS namespace.
  34. */
  35. var C = {};
  36. /**
  37. * Library namespace.
  38. */
  39. var C_lib = C.lib = {};
  40. /**
  41. * Base object for prototypal inheritance.
  42. */
  43. var Base = C_lib.Base = (function () {
  44. return {
  45. /**
  46. * Creates a new object that inherits from this object.
  47. *
  48. * @param {Object} overrides Properties to copy into the new object.
  49. *
  50. * @return {Object} The new object.
  51. *
  52. * @static
  53. *
  54. * @example
  55. *
  56. * var MyType = CryptoJS.lib.Base.extend({
  57. * field: 'value',
  58. *
  59. * method: function () {
  60. * }
  61. * });
  62. */
  63. extend: function (overrides) {
  64. // Spawn
  65. var subtype = create(this);
  66. // Augment
  67. if (overrides) {
  68. subtype.mixIn(overrides);
  69. }
  70. // Create default initializer
  71. if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
  72. subtype.init = function () {
  73. subtype.$super.init.apply(this, arguments);
  74. };
  75. }
  76. // Initializer's prototype is the subtype object
  77. subtype.init.prototype = subtype;
  78. // Reference supertype
  79. subtype.$super = this;
  80. return subtype;
  81. },
  82. /**
  83. * Extends this object and runs the init method.
  84. * Arguments to create() will be passed to init().
  85. *
  86. * @return {Object} The new object.
  87. *
  88. * @static
  89. *
  90. * @example
  91. *
  92. * var instance = MyType.create();
  93. */
  94. create: function () {
  95. var instance = this.extend();
  96. instance.init.apply(instance, arguments);
  97. return instance;
  98. },
  99. /**
  100. * Initializes a newly created object.
  101. * Override this method to add some logic when your objects are created.
  102. *
  103. * @example
  104. *
  105. * var MyType = CryptoJS.lib.Base.extend({
  106. * init: function () {
  107. * // ...
  108. * }
  109. * });
  110. */
  111. init: function () {
  112. },
  113. /**
  114. * Copies properties into this object.
  115. *
  116. * @param {Object} properties The properties to mix in.
  117. *
  118. * @example
  119. *
  120. * MyType.mixIn({
  121. * field: 'value'
  122. * });
  123. */
  124. mixIn: function (properties) {
  125. for (var propertyName in properties) {
  126. if (properties.hasOwnProperty(propertyName)) {
  127. this[propertyName] = properties[propertyName];
  128. }
  129. }
  130. // IE won't copy toString using the loop above
  131. if (properties.hasOwnProperty('toString')) {
  132. this.toString = properties.toString;
  133. }
  134. },
  135. /**
  136. * Creates a copy of this object.
  137. *
  138. * @return {Object} The clone.
  139. *
  140. * @example
  141. *
  142. * var clone = instance.clone();
  143. */
  144. clone: function () {
  145. return this.init.prototype.extend(this);
  146. }
  147. };
  148. }());
  149. /**
  150. * An array of 32-bit words.
  151. *
  152. * @property {Array} words The array of 32-bit words.
  153. * @property {number} sigBytes The number of significant bytes in this word array.
  154. */
  155. var WordArray = C_lib.WordArray = Base.extend({
  156. /**
  157. * Initializes a newly created word array.
  158. *
  159. * @param {Array} words (Optional) An array of 32-bit words.
  160. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  161. *
  162. * @example
  163. *
  164. * var wordArray = CryptoJS.lib.WordArray.create();
  165. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
  166. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
  167. */
  168. init: function (words, sigBytes) {
  169. words = this.words = words || [];
  170. if (sigBytes != undefined) {
  171. this.sigBytes = sigBytes;
  172. } else {
  173. this.sigBytes = words.length * 4;
  174. }
  175. },
  176. /**
  177. * Converts this word array to a string.
  178. *
  179. * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
  180. *
  181. * @return {string} The stringified word array.
  182. *
  183. * @example
  184. *
  185. * var string = wordArray + '';
  186. * var string = wordArray.toString();
  187. * var string = wordArray.toString(CryptoJS.enc.Utf8);
  188. */
  189. toString: function (encoder) {
  190. return (encoder || Hex).stringify(this);
  191. },
  192. /**
  193. * Concatenates a word array to this word array.
  194. *
  195. * @param {WordArray} wordArray The word array to append.
  196. *
  197. * @return {WordArray} This word array.
  198. *
  199. * @example
  200. *
  201. * wordArray1.concat(wordArray2);
  202. */
  203. concat: function (wordArray) {
  204. // Shortcuts
  205. var thisWords = this.words;
  206. var thatWords = wordArray.words;
  207. var thisSigBytes = this.sigBytes;
  208. var thatSigBytes = wordArray.sigBytes;
  209. // Clamp excess bits
  210. this.clamp();
  211. // Concat
  212. if (thisSigBytes % 4) {
  213. // Copy one byte at a time
  214. for (var i = 0; i < thatSigBytes; i++) {
  215. var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  216. thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
  217. }
  218. } else {
  219. // Copy one word at a time
  220. for (var i = 0; i < thatSigBytes; i += 4) {
  221. thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
  222. }
  223. }
  224. this.sigBytes += thatSigBytes;
  225. // Chainable
  226. return this;
  227. },
  228. /**
  229. * Removes insignificant bits.
  230. *
  231. * @example
  232. *
  233. * wordArray.clamp();
  234. */
  235. clamp: function () {
  236. // Shortcuts
  237. var words = this.words;
  238. var sigBytes = this.sigBytes;
  239. // Clamp
  240. words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
  241. words.length = Math.ceil(sigBytes / 4);
  242. },
  243. /**
  244. * Creates a copy of this word array.
  245. *
  246. * @return {WordArray} The clone.
  247. *
  248. * @example
  249. *
  250. * var clone = wordArray.clone();
  251. */
  252. clone: function () {
  253. var clone = Base.clone.call(this);
  254. clone.words = this.words.slice(0);
  255. return clone;
  256. },
  257. /**
  258. * Creates a word array filled with random bytes.
  259. *
  260. * @param {number} nBytes The number of random bytes to generate.
  261. *
  262. * @return {WordArray} The random word array.
  263. *
  264. * @static
  265. *
  266. * @example
  267. *
  268. * var wordArray = CryptoJS.lib.WordArray.random(16);
  269. */
  270. random: function (nBytes) {
  271. var words = [];
  272. var r = (function (m_w) {
  273. var m_w = m_w;
  274. var m_z = 0x3ade68b1;
  275. var mask = 0xffffffff;
  276. return function () {
  277. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  278. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  279. var result = ((m_z << 0x10) + m_w) & mask;
  280. result /= 0x100000000;
  281. result += 0.5;
  282. return result * (Math.random() > .5 ? 1 : -1);
  283. }
  284. });
  285. for (var i = 0, rcache; i < nBytes; i += 4) {
  286. var _r = r((rcache || Math.random()) * 0x100000000);
  287. rcache = _r() * 0x3ade67b7;
  288. words.push((_r() * 0x100000000) | 0);
  289. }
  290. return new WordArray.init(words, nBytes);
  291. }
  292. });
  293. /**
  294. * Encoder namespace.
  295. */
  296. var C_enc = C.enc = {};
  297. /**
  298. * Hex encoding strategy.
  299. */
  300. var Hex = C_enc.Hex = {
  301. /**
  302. * Converts a word array to a hex string.
  303. *
  304. * @param {WordArray} wordArray The word array.
  305. *
  306. * @return {string} The hex string.
  307. *
  308. * @static
  309. *
  310. * @example
  311. *
  312. * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
  313. */
  314. stringify: function (wordArray) {
  315. // Shortcuts
  316. var words = wordArray.words;
  317. var sigBytes = wordArray.sigBytes;
  318. // Convert
  319. var hexChars = [];
  320. for (var i = 0; i < sigBytes; i++) {
  321. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  322. hexChars.push((bite >>> 4).toString(16));
  323. hexChars.push((bite & 0x0f).toString(16));
  324. }
  325. return hexChars.join('');
  326. },
  327. /**
  328. * Converts a hex string to a word array.
  329. *
  330. * @param {string} hexStr The hex string.
  331. *
  332. * @return {WordArray} The word array.
  333. *
  334. * @static
  335. *
  336. * @example
  337. *
  338. * var wordArray = CryptoJS.enc.Hex.parse(hexString);
  339. */
  340. parse: function (hexStr) {
  341. // Shortcut
  342. var hexStrLength = hexStr.length;
  343. // Convert
  344. var words = [];
  345. for (var i = 0; i < hexStrLength; i += 2) {
  346. words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
  347. }
  348. return new WordArray.init(words, hexStrLength / 2);
  349. }
  350. };
  351. /**
  352. * Latin1 encoding strategy.
  353. */
  354. var Latin1 = C_enc.Latin1 = {
  355. /**
  356. * Converts a word array to a Latin1 string.
  357. *
  358. * @param {WordArray} wordArray The word array.
  359. *
  360. * @return {string} The Latin1 string.
  361. *
  362. * @static
  363. *
  364. * @example
  365. *
  366. * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
  367. */
  368. stringify: function (wordArray) {
  369. // Shortcuts
  370. var words = wordArray.words;
  371. var sigBytes = wordArray.sigBytes;
  372. // Convert
  373. var latin1Chars = [];
  374. for (var i = 0; i < sigBytes; i++) {
  375. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  376. latin1Chars.push(String.fromCharCode(bite));
  377. }
  378. return latin1Chars.join('');
  379. },
  380. /**
  381. * Converts a Latin1 string to a word array.
  382. *
  383. * @param {string} latin1Str The Latin1 string.
  384. *
  385. * @return {WordArray} The word array.
  386. *
  387. * @static
  388. *
  389. * @example
  390. *
  391. * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
  392. */
  393. parse: function (latin1Str) {
  394. // Shortcut
  395. var latin1StrLength = latin1Str.length;
  396. // Convert
  397. var words = [];
  398. for (var i = 0; i < latin1StrLength; i++) {
  399. words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
  400. }
  401. return new WordArray.init(words, latin1StrLength);
  402. }
  403. };
  404. /**
  405. * UTF-8 encoding strategy.
  406. */
  407. var Utf8 = C_enc.Utf8 = {
  408. /**
  409. * Converts a word array to a UTF-8 string.
  410. *
  411. * @param {WordArray} wordArray The word array.
  412. *
  413. * @return {string} The UTF-8 string.
  414. *
  415. * @static
  416. *
  417. * @example
  418. *
  419. * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
  420. */
  421. stringify: function (wordArray) {
  422. try {
  423. return decodeURIComponent(escape(Latin1.stringify(wordArray)));
  424. } catch (e) {
  425. throw new Error('Malformed UTF-8 data');
  426. }
  427. },
  428. /**
  429. * Converts a UTF-8 string to a word array.
  430. *
  431. * @param {string} utf8Str The UTF-8 string.
  432. *
  433. * @return {WordArray} The word array.
  434. *
  435. * @static
  436. *
  437. * @example
  438. *
  439. * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
  440. */
  441. parse: function (utf8Str) {
  442. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  443. }
  444. };
  445. /**
  446. * Abstract buffered block algorithm template.
  447. *
  448. * The property blockSize must be implemented in a concrete subtype.
  449. *
  450. * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
  451. */
  452. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
  453. /**
  454. * Resets this block algorithm's data buffer to its initial state.
  455. *
  456. * @example
  457. *
  458. * bufferedBlockAlgorithm.reset();
  459. */
  460. reset: function () {
  461. // Initial values
  462. this._data = new WordArray.init();
  463. this._nDataBytes = 0;
  464. },
  465. /**
  466. * Adds new data to this block algorithm's buffer.
  467. *
  468. * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
  469. *
  470. * @example
  471. *
  472. * bufferedBlockAlgorithm._append('data');
  473. * bufferedBlockAlgorithm._append(wordArray);
  474. */
  475. _append: function (data) {
  476. // Convert string to WordArray, else assume WordArray already
  477. if (typeof data == 'string') {
  478. data = Utf8.parse(data);
  479. }
  480. // Append
  481. this._data.concat(data);
  482. this._nDataBytes += data.sigBytes;
  483. },
  484. /**
  485. * Processes available data blocks.
  486. *
  487. * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
  488. *
  489. * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
  490. *
  491. * @return {WordArray} The processed data.
  492. *
  493. * @example
  494. *
  495. * var processedData = bufferedBlockAlgorithm._process();
  496. * var processedData = bufferedBlockAlgorithm._process(!!'flush');
  497. */
  498. _process: function (doFlush) {
  499. // Shortcuts
  500. var data = this._data;
  501. var dataWords = data.words;
  502. var dataSigBytes = data.sigBytes;
  503. var blockSize = this.blockSize;
  504. var blockSizeBytes = blockSize * 4;
  505. // Count blocks ready
  506. var nBlocksReady = dataSigBytes / blockSizeBytes;
  507. if (doFlush) {
  508. // Round up to include partial blocks
  509. nBlocksReady = Math.ceil(nBlocksReady);
  510. } else {
  511. // Round down to include only full blocks,
  512. // less the number of blocks that must remain in the buffer
  513. nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
  514. }
  515. // Count words ready
  516. var nWordsReady = nBlocksReady * blockSize;
  517. // Count bytes ready
  518. var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
  519. // Process blocks
  520. if (nWordsReady) {
  521. for (var offset = 0; offset < nWordsReady; offset += blockSize) {
  522. // Perform concrete-algorithm logic
  523. this._doProcessBlock(dataWords, offset);
  524. }
  525. // Remove processed words
  526. var processedWords = dataWords.splice(0, nWordsReady);
  527. data.sigBytes -= nBytesReady;
  528. }
  529. // Return processed words
  530. return new WordArray.init(processedWords, nBytesReady);
  531. },
  532. /**
  533. * Creates a copy of this object.
  534. *
  535. * @return {Object} The clone.
  536. *
  537. * @example
  538. *
  539. * var clone = bufferedBlockAlgorithm.clone();
  540. */
  541. clone: function () {
  542. var clone = Base.clone.call(this);
  543. clone._data = this._data.clone();
  544. return clone;
  545. },
  546. _minBufferSize: 0
  547. });
  548. /**
  549. * Abstract hasher template.
  550. *
  551. * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
  552. */
  553. var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
  554. /**
  555. * Configuration options.
  556. */
  557. cfg: Base.extend(),
  558. /**
  559. * Initializes a newly created hasher.
  560. *
  561. * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
  562. *
  563. * @example
  564. *
  565. * var hasher = CryptoJS.algo.SHA256.create();
  566. */
  567. init: function (cfg) {
  568. // Apply config defaults
  569. this.cfg = this.cfg.extend(cfg);
  570. // Set initial values
  571. this.reset();
  572. },
  573. /**
  574. * Resets this hasher to its initial state.
  575. *
  576. * @example
  577. *
  578. * hasher.reset();
  579. */
  580. reset: function () {
  581. // Reset data buffer
  582. BufferedBlockAlgorithm.reset.call(this);
  583. // Perform concrete-hasher logic
  584. this._doReset();
  585. },
  586. /**
  587. * Updates this hasher with a message.
  588. *
  589. * @param {WordArray|string} messageUpdate The message to append.
  590. *
  591. * @return {Hasher} This hasher.
  592. *
  593. * @example
  594. *
  595. * hasher.update('message');
  596. * hasher.update(wordArray);
  597. */
  598. update: function (messageUpdate) {
  599. // Append
  600. this._append(messageUpdate);
  601. // Update the hash
  602. this._process();
  603. // Chainable
  604. return this;
  605. },
  606. /**
  607. * Finalizes the hash computation.
  608. * Note that the finalize operation is effectively a destructive, read-once operation.
  609. *
  610. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  611. *
  612. * @return {WordArray} The hash.
  613. *
  614. * @example
  615. *
  616. * var hash = hasher.finalize();
  617. * var hash = hasher.finalize('message');
  618. * var hash = hasher.finalize(wordArray);
  619. */
  620. finalize: function (messageUpdate) {
  621. // Final message update
  622. if (messageUpdate) {
  623. this._append(messageUpdate);
  624. }
  625. // Perform concrete-hasher logic
  626. var hash = this._doFinalize();
  627. return hash;
  628. },
  629. blockSize: 512/32,
  630. /**
  631. * Creates a shortcut function to a hasher's object interface.
  632. *
  633. * @param {Hasher} hasher The hasher to create a helper for.
  634. *
  635. * @return {Function} The shortcut function.
  636. *
  637. * @static
  638. *
  639. * @example
  640. *
  641. * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
  642. */
  643. _createHelper: function (hasher) {
  644. return function (message, cfg) {
  645. return new hasher.init(cfg).finalize(message);
  646. };
  647. },
  648. /**
  649. * Creates a shortcut function to the HMAC's object interface.
  650. *
  651. * @param {Hasher} hasher The hasher to use in this HMAC helper.
  652. *
  653. * @return {Function} The shortcut function.
  654. *
  655. * @static
  656. *
  657. * @example
  658. *
  659. * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
  660. */
  661. _createHmacHelper: function (hasher) {
  662. return function (message, key) {
  663. return new C_algo.HMAC.init(hasher, key).finalize(message);
  664. };
  665. }
  666. });
  667. /**
  668. * Algorithm namespace.
  669. */
  670. var C_algo = C.algo = {};
  671. return C;
  672. }(Math));
  673. return CryptoJS;
  674. }));