core.js 23 KB

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