core.js 23 KB

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