aes-decrypter.es.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  2. import Stream from '@videojs/vhs-utils/es/stream.js';
  3. import { unpad } from 'pkcs7';
  4. /**
  5. * @file aes.js
  6. *
  7. * This file contains an adaptation of the AES decryption algorithm
  8. * from the Standford Javascript Cryptography Library. That work is
  9. * covered by the following copyright and permissions notice:
  10. *
  11. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or without
  15. * modification, are permitted provided that the following conditions are
  16. * met:
  17. *
  18. * 1. Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * 2. Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  27. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  28. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  29. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  30. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  31. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  32. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  33. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  34. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  35. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  36. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. *
  38. * The views and conclusions contained in the software and documentation
  39. * are those of the authors and should not be interpreted as representing
  40. * official policies, either expressed or implied, of the authors.
  41. */
  42. /**
  43. * Expand the S-box tables.
  44. *
  45. * @private
  46. */
  47. const precompute = function () {
  48. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  49. const encTable = tables[0];
  50. const decTable = tables[1];
  51. const sbox = encTable[4];
  52. const sboxInv = decTable[4];
  53. let i;
  54. let x;
  55. let xInv;
  56. const d = [];
  57. const th = [];
  58. let x2;
  59. let x4;
  60. let x8;
  61. let s;
  62. let tEnc;
  63. let tDec; // Compute double and third tables
  64. for (i = 0; i < 256; i++) {
  65. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  66. }
  67. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  68. // Compute sbox
  69. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  70. s = s >> 8 ^ s & 255 ^ 99;
  71. sbox[x] = s;
  72. sboxInv[s] = x; // Compute MixColumns
  73. x8 = d[x4 = d[x2 = d[x]]];
  74. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  75. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  76. for (i = 0; i < 4; i++) {
  77. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  78. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  79. }
  80. } // Compactify. Considerable speedup on Firefox.
  81. for (i = 0; i < 5; i++) {
  82. encTable[i] = encTable[i].slice(0);
  83. decTable[i] = decTable[i].slice(0);
  84. }
  85. return tables;
  86. };
  87. let aesTables = null;
  88. /**
  89. * Schedule out an AES key for both encryption and decryption. This
  90. * is a low-level class. Use a cipher mode to do bulk encryption.
  91. *
  92. * @class AES
  93. * @param key {Array} The key as an array of 4, 6 or 8 words.
  94. */
  95. class AES {
  96. constructor(key) {
  97. /**
  98. * The expanded S-box and inverse S-box tables. These will be computed
  99. * on the client so that we don't have to send them down the wire.
  100. *
  101. * There are two tables, _tables[0] is for encryption and
  102. * _tables[1] is for decryption.
  103. *
  104. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  105. * last (_tables[01][4]) is the S-box itself.
  106. *
  107. * @private
  108. */
  109. // if we have yet to precompute the S-box tables
  110. // do so now
  111. if (!aesTables) {
  112. aesTables = precompute();
  113. } // then make a copy of that object for use
  114. this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
  115. let i;
  116. let j;
  117. let tmp;
  118. const sbox = this._tables[0][4];
  119. const decTable = this._tables[1];
  120. const keyLen = key.length;
  121. let rcon = 1;
  122. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  123. throw new Error('Invalid aes key size');
  124. }
  125. const encKey = key.slice(0);
  126. const decKey = [];
  127. this._key = [encKey, decKey]; // schedule encryption keys
  128. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  129. tmp = encKey[i - 1]; // apply sbox
  130. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  131. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  132. if (i % keyLen === 0) {
  133. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  134. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  135. }
  136. }
  137. encKey[i] = encKey[i - keyLen] ^ tmp;
  138. } // schedule decryption keys
  139. for (j = 0; i; j++, i--) {
  140. tmp = encKey[j & 3 ? i : i - 4];
  141. if (i <= 4 || j < 4) {
  142. decKey[j] = tmp;
  143. } else {
  144. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  145. }
  146. }
  147. }
  148. /**
  149. * Decrypt 16 bytes, specified as four 32-bit words.
  150. *
  151. * @param {number} encrypted0 the first word to decrypt
  152. * @param {number} encrypted1 the second word to decrypt
  153. * @param {number} encrypted2 the third word to decrypt
  154. * @param {number} encrypted3 the fourth word to decrypt
  155. * @param {Int32Array} out the array to write the decrypted words
  156. * into
  157. * @param {number} offset the offset into the output array to start
  158. * writing results
  159. * @return {Array} The plaintext.
  160. */
  161. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  162. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  163. let a = encrypted0 ^ key[0];
  164. let b = encrypted3 ^ key[1];
  165. let c = encrypted2 ^ key[2];
  166. let d = encrypted1 ^ key[3];
  167. let a2;
  168. let b2;
  169. let c2; // key.length === 2 ?
  170. const nInnerRounds = key.length / 4 - 2;
  171. let i;
  172. let kIndex = 4;
  173. const table = this._tables[1]; // load up the tables
  174. const table0 = table[0];
  175. const table1 = table[1];
  176. const table2 = table[2];
  177. const table3 = table[3];
  178. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  179. for (i = 0; i < nInnerRounds; i++) {
  180. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  181. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  182. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  183. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  184. kIndex += 4;
  185. a = a2;
  186. b = b2;
  187. c = c2;
  188. } // Last round.
  189. for (i = 0; i < 4; i++) {
  190. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  191. a2 = a;
  192. a = b;
  193. b = c;
  194. c = d;
  195. d = a2;
  196. }
  197. }
  198. }
  199. /**
  200. * @file async-stream.js
  201. */
  202. /**
  203. * A wrapper around the Stream class to use setTimeout
  204. * and run stream "jobs" Asynchronously
  205. *
  206. * @class AsyncStream
  207. * @extends Stream
  208. */
  209. class AsyncStream extends Stream {
  210. constructor() {
  211. super(Stream);
  212. this.jobs = [];
  213. this.delay = 1;
  214. this.timeout_ = null;
  215. }
  216. /**
  217. * process an async job
  218. *
  219. * @private
  220. */
  221. processJob_() {
  222. this.jobs.shift()();
  223. if (this.jobs.length) {
  224. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  225. } else {
  226. this.timeout_ = null;
  227. }
  228. }
  229. /**
  230. * push a job into the stream
  231. *
  232. * @param {Function} job the job to push into the stream
  233. */
  234. push(job) {
  235. this.jobs.push(job);
  236. if (!this.timeout_) {
  237. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  238. }
  239. }
  240. }
  241. /**
  242. * @file decrypter.js
  243. *
  244. * An asynchronous implementation of AES-128 CBC decryption with
  245. * PKCS#7 padding.
  246. */
  247. /**
  248. * Convert network-order (big-endian) bytes into their little-endian
  249. * representation.
  250. */
  251. const ntoh = function (word) {
  252. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  253. };
  254. /**
  255. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  256. *
  257. * @param {Uint8Array} encrypted the encrypted bytes
  258. * @param {Uint32Array} key the bytes of the decryption key
  259. * @param {Uint32Array} initVector the initialization vector (IV) to
  260. * use for the first round of CBC.
  261. * @return {Uint8Array} the decrypted bytes
  262. *
  263. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  264. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  265. * @see https://tools.ietf.org/html/rfc2315
  266. */
  267. const decrypt = function (encrypted, key, initVector) {
  268. // word-level access to the encrypted bytes
  269. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  270. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  271. const decrypted = new Uint8Array(encrypted.byteLength);
  272. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  273. // decrypted data
  274. let init0;
  275. let init1;
  276. let init2;
  277. let init3;
  278. let encrypted0;
  279. let encrypted1;
  280. let encrypted2;
  281. let encrypted3; // iteration variable
  282. let wordIx; // pull out the words of the IV to ensure we don't modify the
  283. // passed-in reference and easier access
  284. init0 = initVector[0];
  285. init1 = initVector[1];
  286. init2 = initVector[2];
  287. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  288. // to each decrypted block
  289. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  290. // convert big-endian (network order) words into little-endian
  291. // (javascript order)
  292. encrypted0 = ntoh(encrypted32[wordIx]);
  293. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  294. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  295. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  296. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  297. // plaintext
  298. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  299. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  300. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  301. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  302. init0 = encrypted0;
  303. init1 = encrypted1;
  304. init2 = encrypted2;
  305. init3 = encrypted3;
  306. }
  307. return decrypted;
  308. };
  309. /**
  310. * The `Decrypter` class that manages decryption of AES
  311. * data through `AsyncStream` objects and the `decrypt`
  312. * function
  313. *
  314. * @param {Uint8Array} encrypted the encrypted bytes
  315. * @param {Uint32Array} key the bytes of the decryption key
  316. * @param {Uint32Array} initVector the initialization vector (IV) to
  317. * @param {Function} done the function to run when done
  318. * @class Decrypter
  319. */
  320. class Decrypter {
  321. constructor(encrypted, key, initVector, done) {
  322. const step = Decrypter.STEP;
  323. const encrypted32 = new Int32Array(encrypted.buffer);
  324. const decrypted = new Uint8Array(encrypted.byteLength);
  325. let i = 0;
  326. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  327. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  328. for (i = step; i < encrypted32.length; i += step) {
  329. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  330. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  331. } // invoke the done() callback when everything is finished
  332. this.asyncStream_.push(function () {
  333. // remove pkcs#7 padding from the decrypted bytes
  334. done(null, unpad(decrypted));
  335. });
  336. }
  337. /**
  338. * a getter for step the maximum number of bytes to process at one time
  339. *
  340. * @return {number} the value of step 32000
  341. */
  342. static get STEP() {
  343. // 4 * 8000;
  344. return 32000;
  345. }
  346. /**
  347. * @private
  348. */
  349. decryptChunk_(encrypted, key, initVector, decrypted) {
  350. return function () {
  351. const bytes = decrypt(encrypted, key, initVector);
  352. decrypted.set(bytes, encrypted.byteOffset);
  353. };
  354. }
  355. }
  356. export { AsyncStream, Decrypter, decrypt };