PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/files/crypto-js/3.1.2/components/core.js

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