core.js 24 KB

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