You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1091 lines
38 KiB

4 years ago
  1. /**
  2. * Advanced Encryption Standard (AES) implementation.
  3. *
  4. * This implementation is based on the public domain library 'jscrypto' which
  5. * was written by:
  6. *
  7. * Emily Stark (estark@stanford.edu)
  8. * Mike Hamburg (mhamburg@stanford.edu)
  9. * Dan Boneh (dabo@cs.stanford.edu)
  10. *
  11. * Parts of this code are based on the OpenSSL implementation of AES:
  12. * http://www.openssl.org
  13. *
  14. * @author Dave Longley
  15. *
  16. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  17. */
  18. var forge = require('./forge');
  19. require('./cipher');
  20. require('./cipherModes');
  21. require('./util');
  22. /* AES API */
  23. module.exports = forge.aes = forge.aes || {};
  24. /**
  25. * Deprecated. Instead, use:
  26. *
  27. * var cipher = forge.cipher.createCipher('AES-<mode>', key);
  28. * cipher.start({iv: iv});
  29. *
  30. * Creates an AES cipher object to encrypt data using the given symmetric key.
  31. * The output will be stored in the 'output' member of the returned cipher.
  32. *
  33. * The key and iv may be given as a string of bytes, an array of bytes,
  34. * a byte buffer, or an array of 32-bit words.
  35. *
  36. * @param key the symmetric key to use.
  37. * @param iv the initialization vector to use.
  38. * @param output the buffer to write to, null to create one.
  39. * @param mode the cipher mode to use (default: 'CBC').
  40. *
  41. * @return the cipher.
  42. */
  43. forge.aes.startEncrypting = function(key, iv, output, mode) {
  44. var cipher = _createCipher({
  45. key: key,
  46. output: output,
  47. decrypt: false,
  48. mode: mode
  49. });
  50. cipher.start(iv);
  51. return cipher;
  52. };
  53. /**
  54. * Deprecated. Instead, use:
  55. *
  56. * var cipher = forge.cipher.createCipher('AES-<mode>', key);
  57. *
  58. * Creates an AES cipher object to encrypt data using the given symmetric key.
  59. *
  60. * The key may be given as a string of bytes, an array of bytes, a
  61. * byte buffer, or an array of 32-bit words.
  62. *
  63. * @param key the symmetric key to use.
  64. * @param mode the cipher mode to use (default: 'CBC').
  65. *
  66. * @return the cipher.
  67. */
  68. forge.aes.createEncryptionCipher = function(key, mode) {
  69. return _createCipher({
  70. key: key,
  71. output: null,
  72. decrypt: false,
  73. mode: mode
  74. });
  75. };
  76. /**
  77. * Deprecated. Instead, use:
  78. *
  79. * var decipher = forge.cipher.createDecipher('AES-<mode>', key);
  80. * decipher.start({iv: iv});
  81. *
  82. * Creates an AES cipher object to decrypt data using the given symmetric key.
  83. * The output will be stored in the 'output' member of the returned cipher.
  84. *
  85. * The key and iv may be given as a string of bytes, an array of bytes,
  86. * a byte buffer, or an array of 32-bit words.
  87. *
  88. * @param key the symmetric key to use.
  89. * @param iv the initialization vector to use.
  90. * @param output the buffer to write to, null to create one.
  91. * @param mode the cipher mode to use (default: 'CBC').
  92. *
  93. * @return the cipher.
  94. */
  95. forge.aes.startDecrypting = function(key, iv, output, mode) {
  96. var cipher = _createCipher({
  97. key: key,
  98. output: output,
  99. decrypt: true,
  100. mode: mode
  101. });
  102. cipher.start(iv);
  103. return cipher;
  104. };
  105. /**
  106. * Deprecated. Instead, use:
  107. *
  108. * var decipher = forge.cipher.createDecipher('AES-<mode>', key);
  109. *
  110. * Creates an AES cipher object to decrypt data using the given symmetric key.
  111. *
  112. * The key may be given as a string of bytes, an array of bytes, a
  113. * byte buffer, or an array of 32-bit words.
  114. *
  115. * @param key the symmetric key to use.
  116. * @param mode the cipher mode to use (default: 'CBC').
  117. *
  118. * @return the cipher.
  119. */
  120. forge.aes.createDecryptionCipher = function(key, mode) {
  121. return _createCipher({
  122. key: key,
  123. output: null,
  124. decrypt: true,
  125. mode: mode
  126. });
  127. };
  128. /**
  129. * Creates a new AES cipher algorithm object.
  130. *
  131. * @param name the name of the algorithm.
  132. * @param mode the mode factory function.
  133. *
  134. * @return the AES algorithm object.
  135. */
  136. forge.aes.Algorithm = function(name, mode) {
  137. if(!init) {
  138. initialize();
  139. }
  140. var self = this;
  141. self.name = name;
  142. self.mode = new mode({
  143. blockSize: 16,
  144. cipher: {
  145. encrypt: function(inBlock, outBlock) {
  146. return _updateBlock(self._w, inBlock, outBlock, false);
  147. },
  148. decrypt: function(inBlock, outBlock) {
  149. return _updateBlock(self._w, inBlock, outBlock, true);
  150. }
  151. }
  152. });
  153. self._init = false;
  154. };
  155. /**
  156. * Initializes this AES algorithm by expanding its key.
  157. *
  158. * @param options the options to use.
  159. * key the key to use with this algorithm.
  160. * decrypt true if the algorithm should be initialized for decryption,
  161. * false for encryption.
  162. */
  163. forge.aes.Algorithm.prototype.initialize = function(options) {
  164. if(this._init) {
  165. return;
  166. }
  167. var key = options.key;
  168. var tmp;
  169. /* Note: The key may be a string of bytes, an array of bytes, a byte
  170. buffer, or an array of 32-bit integers. If the key is in bytes, then
  171. it must be 16, 24, or 32 bytes in length. If it is in 32-bit
  172. integers, it must be 4, 6, or 8 integers long. */
  173. if(typeof key === 'string' &&
  174. (key.length === 16 || key.length === 24 || key.length === 32)) {
  175. // convert key string into byte buffer
  176. key = forge.util.createBuffer(key);
  177. } else if(forge.util.isArray(key) &&
  178. (key.length === 16 || key.length === 24 || key.length === 32)) {
  179. // convert key integer array into byte buffer
  180. tmp = key;
  181. key = forge.util.createBuffer();
  182. for(var i = 0; i < tmp.length; ++i) {
  183. key.putByte(tmp[i]);
  184. }
  185. }
  186. // convert key byte buffer into 32-bit integer array
  187. if(!forge.util.isArray(key)) {
  188. tmp = key;
  189. key = [];
  190. // key lengths of 16, 24, 32 bytes allowed
  191. var len = tmp.length();
  192. if(len === 16 || len === 24 || len === 32) {
  193. len = len >>> 2;
  194. for(var i = 0; i < len; ++i) {
  195. key.push(tmp.getInt32());
  196. }
  197. }
  198. }
  199. // key must be an array of 32-bit integers by now
  200. if(!forge.util.isArray(key) ||
  201. !(key.length === 4 || key.length === 6 || key.length === 8)) {
  202. throw new Error('Invalid key parameter.');
  203. }
  204. // encryption operation is always used for these modes
  205. var mode = this.mode.name;
  206. var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);
  207. // do key expansion
  208. this._w = _expandKey(key, options.decrypt && !encryptOp);
  209. this._init = true;
  210. };
  211. /**
  212. * Expands a key. Typically only used for testing.
  213. *
  214. * @param key the symmetric key to expand, as an array of 32-bit words.
  215. * @param decrypt true to expand for decryption, false for encryption.
  216. *
  217. * @return the expanded key.
  218. */
  219. forge.aes._expandKey = function(key, decrypt) {
  220. if(!init) {
  221. initialize();
  222. }
  223. return _expandKey(key, decrypt);
  224. };
  225. /**
  226. * Updates a single block. Typically only used for testing.
  227. *
  228. * @param w the expanded key to use.
  229. * @param input an array of block-size 32-bit words.
  230. * @param output an array of block-size 32-bit words.
  231. * @param decrypt true to decrypt, false to encrypt.
  232. */
  233. forge.aes._updateBlock = _updateBlock;
  234. /** Register AES algorithms **/
  235. registerAlgorithm('AES-ECB', forge.cipher.modes.ecb);
  236. registerAlgorithm('AES-CBC', forge.cipher.modes.cbc);
  237. registerAlgorithm('AES-CFB', forge.cipher.modes.cfb);
  238. registerAlgorithm('AES-OFB', forge.cipher.modes.ofb);
  239. registerAlgorithm('AES-CTR', forge.cipher.modes.ctr);
  240. registerAlgorithm('AES-GCM', forge.cipher.modes.gcm);
  241. function registerAlgorithm(name, mode) {
  242. var factory = function() {
  243. return new forge.aes.Algorithm(name, mode);
  244. };
  245. forge.cipher.registerAlgorithm(name, factory);
  246. }
  247. /** AES implementation **/
  248. var init = false; // not yet initialized
  249. var Nb = 4; // number of words comprising the state (AES = 4)
  250. var sbox; // non-linear substitution table used in key expansion
  251. var isbox; // inversion of sbox
  252. var rcon; // round constant word array
  253. var mix; // mix-columns table
  254. var imix; // inverse mix-columns table
  255. /**
  256. * Performs initialization, ie: precomputes tables to optimize for speed.
  257. *
  258. * One way to understand how AES works is to imagine that 'addition' and
  259. * 'multiplication' are interfaces that require certain mathematical
  260. * properties to hold true (ie: they are associative) but they might have
  261. * different implementations and produce different kinds of results ...
  262. * provided that their mathematical properties remain true. AES defines
  263. * its own methods of addition and multiplication but keeps some important
  264. * properties the same, ie: associativity and distributivity. The
  265. * explanation below tries to shed some light on how AES defines addition
  266. * and multiplication of bytes and 32-bit words in order to perform its
  267. * encryption and decryption algorithms.
  268. *
  269. * The basics:
  270. *
  271. * The AES algorithm views bytes as binary representations of polynomials
  272. * that have either 1 or 0 as the coefficients. It defines the addition
  273. * or subtraction of two bytes as the XOR operation. It also defines the
  274. * multiplication of two bytes as a finite field referred to as GF(2^8)
  275. * (Note: 'GF' means "Galois Field" which is a field that contains a finite
  276. * number of elements so GF(2^8) has 256 elements).
  277. *
  278. * This means that any two bytes can be represented as binary polynomials;
  279. * when they multiplied together and modularly reduced by an irreducible
  280. * polynomial of the 8th degree, the results are the field GF(2^8). The
  281. * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.
  282. * This multiplication is associative with 0x01 as the identity:
  283. *
  284. * (b * 0x01 = GF(b, 0x01) = b).
  285. *
  286. * The operation GF(b, 0x02) can be performed at the byte level by left
  287. * shifting b once and then XOR'ing it (to perform the modular reduction)
  288. * with 0x11b if b is >= 128. Repeated application of the multiplication
  289. * of 0x02 can be used to implement the multiplication of any two bytes.
  290. *
  291. * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can
  292. * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these
  293. * factors can each be multiplied by 0x57 and then added together. To do
  294. * the multiplication, values for 0x57 multiplied by each of these 3 factors
  295. * can be precomputed and stored in a table. To add them, the values from
  296. * the table are XOR'd together.
  297. *
  298. * AES also defines addition and multiplication of words, that is 4-byte
  299. * numbers represented as polynomials of 3 degrees where the coefficients
  300. * are the values of the bytes.
  301. *
  302. * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.
  303. *
  304. * Addition is performed by XOR'ing like powers of x. Multiplication
  305. * is performed in two steps, the first is an algebriac expansion as
  306. * you would do normally (where addition is XOR). But the result is
  307. * a polynomial larger than 3 degrees and thus it cannot fit in a word. So
  308. * next the result is modularly reduced by an AES-specific polynomial of
  309. * degree 4 which will always produce a polynomial of less than 4 degrees
  310. * such that it will fit in a word. In AES, this polynomial is x^4 + 1.
  311. *
  312. * The modular product of two polynomials 'a' and 'b' is thus:
  313. *
  314. * d(x) = d3x^3 + d2x^2 + d1x + d0
  315. * with
  316. * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)
  317. * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)
  318. * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)
  319. * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)
  320. *
  321. * As a matrix:
  322. *
  323. * [d0] = [a0 a3 a2 a1][b0]
  324. * [d1] [a1 a0 a3 a2][b1]
  325. * [d2] [a2 a1 a0 a3][b2]
  326. * [d3] [a3 a2 a1 a0][b3]
  327. *
  328. * Special polynomials defined by AES (0x02 == {02}):
  329. * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}
  330. * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.
  331. *
  332. * These polynomials are used in the MixColumns() and InverseMixColumns()
  333. * operations, respectively, to cause each element in the state to affect
  334. * the output (referred to as diffusing).
  335. *
  336. * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the
  337. * polynomial x3.
  338. *
  339. * The ShiftRows() method modifies the last 3 rows in the state (where
  340. * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.
  341. * The 1st byte in the second row is moved to the end of the row. The 1st
  342. * and 2nd bytes in the third row are moved to the end of the row. The 1st,
  343. * 2nd, and 3rd bytes are moved in the fourth row.
  344. *
  345. * More details on how AES arithmetic works:
  346. *
  347. * In the polynomial representation of binary numbers, XOR performs addition
  348. * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)
  349. * corresponds with the multiplication of polynomials modulo an irreducible
  350. * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply
  351. * polynomial 'a' with polynomial 'b' and then do a modular reduction by
  352. * an AES-specific irreducible polynomial of degree 8.
  353. *
  354. * A polynomial is irreducible if its only divisors are one and itself. For
  355. * the AES algorithm, this irreducible polynomial is:
  356. *
  357. * m(x) = x^8 + x^4 + x^3 + x + 1,
  358. *
  359. * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:
  360. * 100011011 = 283 = 0x11b.
  361. *
  362. * For example, GF(0x57, 0x83) = 0xc1 because
  363. *
  364. * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1
  365. * 0x85 = 131 = 10000101 = x^7 + x + 1
  366. *
  367. * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)
  368. * = x^13 + x^11 + x^9 + x^8 + x^7 +
  369. * x^7 + x^5 + x^3 + x^2 + x +
  370. * x^6 + x^4 + x^2 + x + 1
  371. * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y
  372. * y modulo (x^8 + x^4 + x^3 + x + 1)
  373. * = x^7 + x^6 + 1.
  374. *
  375. * The modular reduction by m(x) guarantees the result will be a binary
  376. * polynomial of less than degree 8, so that it can fit in a byte.
  377. *
  378. * The operation to multiply a binary polynomial b with x (the polynomial
  379. * x in binary representation is 00000010) is:
  380. *
  381. * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1
  382. *
  383. * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the
  384. * most significant bit is 0 in b) then the result is already reduced. If
  385. * it is 1, then we can reduce it by subtracting m(x) via an XOR.
  386. *
  387. * It follows that multiplication by x (00000010 or 0x02) can be implemented
  388. * by performing a left shift followed by a conditional bitwise XOR with
  389. * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by
  390. * higher powers of x can be implemented by repeated application of xtime().
  391. *
  392. * By adding intermediate results, multiplication by any constant can be
  393. * implemented. For instance:
  394. *
  395. * GF(0x57, 0x13) = 0xfe because:
  396. *
  397. * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)
  398. *
  399. * Note: We XOR with 0x11b instead of 0x1b because in javascript our
  400. * datatype for b can be larger than 1 byte, so a left shift will not
  401. * automatically eliminate bits that overflow a byte ... by XOR'ing the
  402. * overflow bit with 1 (the extra one from 0x11b) we zero it out.
  403. *
  404. * GF(0x57, 0x02) = xtime(0x57) = 0xae
  405. * GF(0x57, 0x04) = xtime(0xae) = 0x47
  406. * GF(0x57, 0x08) = xtime(0x47) = 0x8e
  407. * GF(0x57, 0x10) = xtime(0x8e) = 0x07
  408. *
  409. * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))
  410. *
  411. * And by the distributive property (since XOR is addition and GF() is
  412. * multiplication):
  413. *
  414. * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)
  415. * = 0x57 ^ 0xae ^ 0x07
  416. * = 0xfe.
  417. */
  418. function initialize() {
  419. init = true;
  420. /* Populate the Rcon table. These are the values given by
  421. [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)
  422. in the field of GF(2^8), where i starts at 1.
  423. rcon[0] = [0x00, 0x00, 0x00, 0x00]
  424. rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1
  425. rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2
  426. ...
  427. rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B
  428. rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36
  429. We only store the first byte because it is the only one used.
  430. */
  431. rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];
  432. // compute xtime table which maps i onto GF(i, 0x02)
  433. var xtime = new Array(256);
  434. for(var i = 0; i < 128; ++i) {
  435. xtime[i] = i << 1;
  436. xtime[i + 128] = (i + 128) << 1 ^ 0x11B;
  437. }
  438. // compute all other tables
  439. sbox = new Array(256);
  440. isbox = new Array(256);
  441. mix = new Array(4);
  442. imix = new Array(4);
  443. for(var i = 0; i < 4; ++i) {
  444. mix[i] = new Array(256);
  445. imix[i] = new Array(256);
  446. }
  447. var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;
  448. for(var i = 0; i < 256; ++i) {
  449. /* We need to generate the SubBytes() sbox and isbox tables so that
  450. we can perform byte substitutions. This requires us to traverse
  451. all of the elements in GF, find their multiplicative inverses,
  452. and apply to each the following affine transformation:
  453. bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^
  454. b(i + 7) mod 8 ^ ci
  455. for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the
  456. ith bit of a byte c with the value {63} or {01100011}.
  457. It is possible to traverse every possible value in a Galois field
  458. using what is referred to as a 'generator'. There are many
  459. generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully
  460. traverse GF we iterate 255 times, multiplying by our generator
  461. each time.
  462. On each iteration we can determine the multiplicative inverse for
  463. the current element.
  464. Suppose there is an element in GF 'e'. For a given generator 'g',
  465. e = g^x. The multiplicative inverse of e is g^(255 - x). It turns
  466. out that if use the inverse of a generator as another generator
  467. it will produce all of the corresponding multiplicative inverses
  468. at the same time. For this reason, we choose 5 as our inverse
  469. generator because it only requires 2 multiplies and 1 add and its
  470. inverse, 82, requires relatively few operations as well.
  471. In order to apply the affine transformation, the multiplicative
  472. inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a
  473. bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and
  474. 'x'. Then 's' is left shifted and the high bit of 's' is made the
  475. low bit. The resulting value is stored in 's'. Then 'x' is XOR'd
  476. with 's' and stored in 'x'. On each subsequent iteration the same
  477. operation is performed. When 4 iterations are complete, 'x' is
  478. XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.
  479. For example:
  480. s = 01000001
  481. x = 01000001
  482. iteration 1: s = 10000010, x ^= s
  483. iteration 2: s = 00000101, x ^= s
  484. iteration 3: s = 00001010, x ^= s
  485. iteration 4: s = 00010100, x ^= s
  486. x ^= 0x63
  487. This can be done with a loop where s = (s << 1) | (s >> 7). However,
  488. it can also be done by using a single 16-bit (in this case 32-bit)
  489. number 'sx'. Since XOR is an associative operation, we can set 'sx'
  490. to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.
  491. The most significant bits will flow into the high 8 bit positions
  492. and be correctly XOR'd with one another. All that remains will be
  493. to cycle the high 8 bits by XOR'ing them all with the lower 8 bits
  494. afterwards.
  495. At the same time we're populating sbox and isbox we can precompute
  496. the multiplication we'll need to do to do MixColumns() later.
  497. */
  498. // apply affine transformation
  499. sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);
  500. sx = (sx >> 8) ^ (sx & 255) ^ 0x63;
  501. // update tables
  502. sbox[e] = sx;
  503. isbox[sx] = e;
  504. /* Mixing columns is done using matrix multiplication. The columns
  505. that are to be mixed are each a single word in the current state.
  506. The state has Nb columns (4 columns). Therefore each column is a
  507. 4 byte word. So to mix the columns in a single column 'c' where
  508. its rows are r0, r1, r2, and r3, we use the following matrix
  509. multiplication:
  510. [2 3 1 1]*[r0,c]=[r'0,c]
  511. [1 2 3 1] [r1,c] [r'1,c]
  512. [1 1 2 3] [r2,c] [r'2,c]
  513. [3 1 1 2] [r3,c] [r'3,c]
  514. r0, r1, r2, and r3 are each 1 byte of one of the words in the
  515. state (a column). To do matrix multiplication for each mixed
  516. column c' we multiply the corresponding row from the left matrix
  517. with the corresponding column from the right matrix. In total, we
  518. get 4 equations:
  519. r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c
  520. r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c
  521. r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c
  522. r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c
  523. As usual, the multiplication is as previously defined and the
  524. addition is XOR. In order to optimize mixing columns we can store
  525. the multiplication results in tables. If you think of the whole
  526. column as a word (it might help to visualize by mentally rotating
  527. the equations above by counterclockwise 90 degrees) then you can
  528. see that it would be useful to map the multiplications performed on
  529. each byte (r0, r1, r2, r3) onto a word as well. For instance, we
  530. could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the
  531. highest 8 bits and 3*r0 in the lowest 8 bits (with the other two
  532. respectively in the middle). This means that a table can be
  533. constructed that uses r0 as an index to the word. We can do the
  534. same with r1, r2, and r3, creating a total of 4 tables.
  535. To construct a full c', we can just look up each byte of c in
  536. their respective tables and XOR the results together.
  537. Also, to build each table we only have to calculate the word
  538. for 2,1,1,3 for every byte ... which we can do on each iteration
  539. of this loop since we will iterate over every byte. After we have
  540. calculated 2,1,1,3 we can get the results for the other tables
  541. by cycling the byte at the end to the beginning. For instance
  542. we can take the result of table 2,1,1,3 and produce table 3,2,1,1
  543. by moving the right most byte to the left most position just like
  544. how you can imagine the 3 moved out of 2,1,1,3 and to the front
  545. to produce 3,2,1,1.
  546. There is another optimization in that the same multiples of
  547. the current element we need in order to advance our generator
  548. to the next iteration can be reused in performing the 2,1,1,3
  549. calculation. We also calculate the inverse mix column tables,
  550. with e,9,d,b being the inverse of 2,1,1,3.
  551. When we're done, and we need to actually mix columns, the first
  552. byte of each state word should be put through mix[0] (2,1,1,3),
  553. the second through mix[1] (3,2,1,1) and so forth. Then they should
  554. be XOR'd together to produce the fully mixed column.
  555. */
  556. // calculate mix and imix table values
  557. sx2 = xtime[sx];
  558. e2 = xtime[e];
  559. e4 = xtime[e2];
  560. e8 = xtime[e4];
  561. me =
  562. (sx2 << 24) ^ // 2
  563. (sx << 16) ^ // 1
  564. (sx << 8) ^ // 1
  565. (sx ^ sx2); // 3
  566. ime =
  567. (e2 ^ e4 ^ e8) << 24 ^ // E (14)
  568. (e ^ e8) << 16 ^ // 9
  569. (e ^ e4 ^ e8) << 8 ^ // D (13)
  570. (e ^ e2 ^ e8); // B (11)
  571. // produce each of the mix tables by rotating the 2,1,1,3 value
  572. for(var n = 0; n < 4; ++n) {
  573. mix[n][e] = me;
  574. imix[n][sx] = ime;
  575. // cycle the right most byte to the left most position
  576. // ie: 2,1,1,3 becomes 3,2,1,1
  577. me = me << 24 | me >>> 8;
  578. ime = ime << 24 | ime >>> 8;
  579. }
  580. // get next element and inverse
  581. if(e === 0) {
  582. // 1 is the inverse of 1
  583. e = ei = 1;
  584. } else {
  585. // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)
  586. // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)
  587. e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];
  588. ei ^= xtime[xtime[ei]];
  589. }
  590. }
  591. }
  592. /**
  593. * Generates a key schedule using the AES key expansion algorithm.
  594. *
  595. * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion
  596. * routine to generate a key schedule. The Key Expansion generates a total
  597. * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,
  598. * and each of the Nr rounds requires Nb words of key data. The resulting
  599. * key schedule consists of a linear array of 4-byte words, denoted [wi ],
  600. * with i in the range 0 <= i < Nb(Nr + 1).
  601. *
  602. * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)
  603. * AES-128 (Nb=4, Nk=4, Nr=10)
  604. * AES-192 (Nb=4, Nk=6, Nr=12)
  605. * AES-256 (Nb=4, Nk=8, Nr=14)
  606. * Note: Nr=Nk+6.
  607. *
  608. * Nb is the number of columns (32-bit words) comprising the State (or
  609. * number of bytes in a block). For AES, Nb=4.
  610. *
  611. * @param key the key to schedule (as an array of 32-bit words).
  612. * @param decrypt true to modify the key schedule to decrypt, false not to.
  613. *
  614. * @return the generated key schedule.
  615. */
  616. function _expandKey(key, decrypt) {
  617. // copy the key's words to initialize the key schedule
  618. var w = key.slice(0);
  619. /* RotWord() will rotate a word, moving the first byte to the last
  620. byte's position (shifting the other bytes left).
  621. We will be getting the value of Rcon at i / Nk. 'i' will iterate
  622. from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in
  623. a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from
  624. 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will
  625. increase by 1. We use a counter iNk to keep track of this.
  626. */
  627. // go through the rounds expanding the key
  628. var temp, iNk = 1;
  629. var Nk = w.length;
  630. var Nr1 = Nk + 6 + 1;
  631. var end = Nb * Nr1;
  632. for(var i = Nk; i < end; ++i) {
  633. temp = w[i - 1];
  634. if(i % Nk === 0) {
  635. // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]
  636. temp =
  637. sbox[temp >>> 16 & 255] << 24 ^
  638. sbox[temp >>> 8 & 255] << 16 ^
  639. sbox[temp & 255] << 8 ^
  640. sbox[temp >>> 24] ^ (rcon[iNk] << 24);
  641. iNk++;
  642. } else if(Nk > 6 && (i % Nk === 4)) {
  643. // temp = SubWord(temp)
  644. temp =
  645. sbox[temp >>> 24] << 24 ^
  646. sbox[temp >>> 16 & 255] << 16 ^
  647. sbox[temp >>> 8 & 255] << 8 ^
  648. sbox[temp & 255];
  649. }
  650. w[i] = w[i - Nk] ^ temp;
  651. }
  652. /* When we are updating a cipher block we always use the code path for
  653. encryption whether we are decrypting or not (to shorten code and
  654. simplify the generation of look up tables). However, because there
  655. are differences in the decryption algorithm, other than just swapping
  656. in different look up tables, we must transform our key schedule to
  657. account for these changes:
  658. 1. The decryption algorithm gets its key rounds in reverse order.
  659. 2. The decryption algorithm adds the round key before mixing columns
  660. instead of afterwards.
  661. We don't need to modify our key schedule to handle the first case,
  662. we can just traverse the key schedule in reverse order when decrypting.
  663. The second case requires a little work.
  664. The tables we built for performing rounds will take an input and then
  665. perform SubBytes() and MixColumns() or, for the decrypt version,
  666. InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires
  667. us to AddRoundKey() before InvMixColumns(). This means we'll need to
  668. apply some transformations to the round key to inverse-mix its columns
  669. so they'll be correct for moving AddRoundKey() to after the state has
  670. had its columns inverse-mixed.
  671. To inverse-mix the columns of the state when we're decrypting we use a
  672. lookup table that will apply InvSubBytes() and InvMixColumns() at the
  673. same time. However, the round key's bytes are not inverse-substituted
  674. in the decryption algorithm. To get around this problem, we can first
  675. substitute the bytes in the round key so that when we apply the
  676. transformation via the InvSubBytes()+InvMixColumns() table, it will
  677. undo our substitution leaving us with the original value that we
  678. want -- and then inverse-mix that value.
  679. This change will correctly alter our key schedule so that we can XOR
  680. each round key with our already transformed decryption state. This
  681. allows us to use the same code path as the encryption algorithm.
  682. We make one more change to the decryption key. Since the decryption
  683. algorithm runs in reverse from the encryption algorithm, we reverse
  684. the order of the round keys to avoid having to iterate over the key
  685. schedule backwards when running the encryption algorithm later in
  686. decryption mode. In addition to reversing the order of the round keys,
  687. we also swap each round key's 2nd and 4th rows. See the comments
  688. section where rounds are performed for more details about why this is
  689. done. These changes are done inline with the other substitution
  690. described above.
  691. */
  692. if(decrypt) {
  693. var tmp;
  694. var m0 = imix[0];
  695. var m1 = imix[1];
  696. var m2 = imix[2];
  697. var m3 = imix[3];
  698. var wnew = w.slice(0);
  699. end = w.length;
  700. for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {
  701. // do not sub the first or last round key (round keys are Nb
  702. // words) as no column mixing is performed before they are added,
  703. // but do change the key order
  704. if(i === 0 || i === (end - Nb)) {
  705. wnew[i] = w[wi];
  706. wnew[i + 1] = w[wi + 3];
  707. wnew[i + 2] = w[wi + 2];
  708. wnew[i + 3] = w[wi + 1];
  709. } else {
  710. // substitute each round key byte because the inverse-mix
  711. // table will inverse-substitute it (effectively cancel the
  712. // substitution because round key bytes aren't sub'd in
  713. // decryption mode) and swap indexes 3 and 1
  714. for(var n = 0; n < Nb; ++n) {
  715. tmp = w[wi + n];
  716. wnew[i + (3&-n)] =
  717. m0[sbox[tmp >>> 24]] ^
  718. m1[sbox[tmp >>> 16 & 255]] ^
  719. m2[sbox[tmp >>> 8 & 255]] ^
  720. m3[sbox[tmp & 255]];
  721. }
  722. }
  723. }
  724. w = wnew;
  725. }
  726. return w;
  727. }
  728. /**
  729. * Updates a single block (16 bytes) using AES. The update will either
  730. * encrypt or decrypt the block.
  731. *
  732. * @param w the key schedule.
  733. * @param input the input block (an array of 32-bit words).
  734. * @param output the updated output block.
  735. * @param decrypt true to decrypt the block, false to encrypt it.
  736. */
  737. function _updateBlock(w, input, output, decrypt) {
  738. /*
  739. Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
  740. begin
  741. byte state[4,Nb]
  742. state = in
  743. AddRoundKey(state, w[0, Nb-1])
  744. for round = 1 step 1 to Nr-1
  745. SubBytes(state)
  746. ShiftRows(state)
  747. MixColumns(state)
  748. AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
  749. end for
  750. SubBytes(state)
  751. ShiftRows(state)
  752. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  753. out = state
  754. end
  755. InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
  756. begin
  757. byte state[4,Nb]
  758. state = in
  759. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  760. for round = Nr-1 step -1 downto 1
  761. InvShiftRows(state)
  762. InvSubBytes(state)
  763. AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
  764. InvMixColumns(state)
  765. end for
  766. InvShiftRows(state)
  767. InvSubBytes(state)
  768. AddRoundKey(state, w[0, Nb-1])
  769. out = state
  770. end
  771. */
  772. // Encrypt: AddRoundKey(state, w[0, Nb-1])
  773. // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  774. var Nr = w.length / 4 - 1;
  775. var m0, m1, m2, m3, sub;
  776. if(decrypt) {
  777. m0 = imix[0];
  778. m1 = imix[1];
  779. m2 = imix[2];
  780. m3 = imix[3];
  781. sub = isbox;
  782. } else {
  783. m0 = mix[0];
  784. m1 = mix[1];
  785. m2 = mix[2];
  786. m3 = mix[3];
  787. sub = sbox;
  788. }
  789. var a, b, c, d, a2, b2, c2;
  790. a = input[0] ^ w[0];
  791. b = input[decrypt ? 3 : 1] ^ w[1];
  792. c = input[2] ^ w[2];
  793. d = input[decrypt ? 1 : 3] ^ w[3];
  794. var i = 3;
  795. /* In order to share code we follow the encryption algorithm when both
  796. encrypting and decrypting. To account for the changes required in the
  797. decryption algorithm, we use different lookup tables when decrypting
  798. and use a modified key schedule to account for the difference in the
  799. order of transformations applied when performing rounds. We also get
  800. key rounds in reverse order (relative to encryption). */
  801. for(var round = 1; round < Nr; ++round) {
  802. /* As described above, we'll be using table lookups to perform the
  803. column mixing. Each column is stored as a word in the state (the
  804. array 'input' has one column as a word at each index). In order to
  805. mix a column, we perform these transformations on each row in c,
  806. which is 1 byte in each word. The new column for c0 is c'0:
  807. m0 m1 m2 m3
  808. r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0
  809. r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0
  810. r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0
  811. r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0
  812. So using mix tables where c0 is a word with r0 being its upper
  813. 8 bits and r3 being its lower 8 bits:
  814. m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]
  815. ...
  816. m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]
  817. Therefore to mix the columns in each word in the state we
  818. do the following (& 255 omitted for brevity):
  819. c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  820. c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  821. c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  822. c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  823. However, before mixing, the algorithm requires us to perform
  824. ShiftRows(). The ShiftRows() transformation cyclically shifts the
  825. last 3 rows of the state over different offsets. The first row
  826. (r = 0) is not shifted.
  827. s'_r,c = s_r,(c + shift(r, Nb) mod Nb
  828. for 0 < r < 4 and 0 <= c < Nb and
  829. shift(1, 4) = 1
  830. shift(2, 4) = 2
  831. shift(3, 4) = 3.
  832. This causes the first byte in r = 1 to be moved to the end of
  833. the row, the first 2 bytes in r = 2 to be moved to the end of
  834. the row, the first 3 bytes in r = 3 to be moved to the end of
  835. the row:
  836. r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]
  837. r2: [c0 c1 c2 c3] [c2 c3 c0 c1]
  838. r3: [c0 c1 c2 c3] [c3 c0 c1 c2]
  839. We can make these substitutions inline with our column mixing to
  840. generate an updated set of equations to produce each word in the
  841. state (note the columns have changed positions):
  842. c0 c1 c2 c3 => c0 c1 c2 c3
  843. c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)
  844. c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)
  845. c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)
  846. Therefore:
  847. c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3
  848. c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3
  849. c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3
  850. c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3
  851. c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0
  852. c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0
  853. c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0
  854. c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0
  855. ... and so forth for c'2 and c'3. The important distinction is
  856. that the columns are cycling, with c0 being used with the m0
  857. map when calculating c0, but c1 being used with the m0 map when
  858. calculating c1 ... and so forth.
  859. When performing the inverse we transform the mirror image and
  860. skip the bottom row, instead of the top one, and move upwards:
  861. c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption
  862. c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)
  863. c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption
  864. c3 c2 c1 c0 c3 c2 c1 c0
  865. If you compare the resulting matrices for ShiftRows()+MixColumns()
  866. and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are
  867. different (in encrypt mode vs. decrypt mode). So in order to use
  868. the same code to handle both encryption and decryption, we will
  869. need to do some mapping.
  870. If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r<N> be
  871. a row number in the state, then the resulting matrix in encryption
  872. mode for applying the above transformations would be:
  873. r1: a b c d
  874. r2: b c d a
  875. r3: c d a b
  876. r4: d a b c
  877. If we did the same in decryption mode we would get:
  878. r1: a d c b
  879. r2: b a d c
  880. r3: c b a d
  881. r4: d c b a
  882. If instead we swap d and b (set b=c3 and d=c1), then we get:
  883. r1: a b c d
  884. r2: d a b c
  885. r3: c d a b
  886. r4: b c d a
  887. Now the 1st and 3rd rows are the same as the encryption matrix. All
  888. we need to do then to make the mapping exactly the same is to swap
  889. the 2nd and 4th rows when in decryption mode. To do this without
  890. having to do it on each iteration, we swapped the 2nd and 4th rows
  891. in the decryption key schedule. We also have to do the swap above
  892. when we first pull in the input and when we set the final output. */
  893. a2 =
  894. m0[a >>> 24] ^
  895. m1[b >>> 16 & 255] ^
  896. m2[c >>> 8 & 255] ^
  897. m3[d & 255] ^ w[++i];
  898. b2 =
  899. m0[b >>> 24] ^
  900. m1[c >>> 16 & 255] ^
  901. m2[d >>> 8 & 255] ^
  902. m3[a & 255] ^ w[++i];
  903. c2 =
  904. m0[c >>> 24] ^
  905. m1[d >>> 16 & 255] ^
  906. m2[a >>> 8 & 255] ^
  907. m3[b & 255] ^ w[++i];
  908. d =
  909. m0[d >>> 24] ^
  910. m1[a >>> 16 & 255] ^
  911. m2[b >>> 8 & 255] ^
  912. m3[c & 255] ^ w[++i];
  913. a = a2;
  914. b = b2;
  915. c = c2;
  916. }
  917. /*
  918. Encrypt:
  919. SubBytes(state)
  920. ShiftRows(state)
  921. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  922. Decrypt:
  923. InvShiftRows(state)
  924. InvSubBytes(state)
  925. AddRoundKey(state, w[0, Nb-1])
  926. */
  927. // Note: rows are shifted inline
  928. output[0] =
  929. (sub[a >>> 24] << 24) ^
  930. (sub[b >>> 16 & 255] << 16) ^
  931. (sub[c >>> 8 & 255] << 8) ^
  932. (sub[d & 255]) ^ w[++i];
  933. output[decrypt ? 3 : 1] =
  934. (sub[b >>> 24] << 24) ^
  935. (sub[c >>> 16 & 255] << 16) ^
  936. (sub[d >>> 8 & 255] << 8) ^
  937. (sub[a & 255]) ^ w[++i];
  938. output[2] =
  939. (sub[c >>> 24] << 24) ^
  940. (sub[d >>> 16 & 255] << 16) ^
  941. (sub[a >>> 8 & 255] << 8) ^
  942. (sub[b & 255]) ^ w[++i];
  943. output[decrypt ? 1 : 3] =
  944. (sub[d >>> 24] << 24) ^
  945. (sub[a >>> 16 & 255] << 16) ^
  946. (sub[b >>> 8 & 255] << 8) ^
  947. (sub[c & 255]) ^ w[++i];
  948. }
  949. /**
  950. * Deprecated. Instead, use:
  951. *
  952. * forge.cipher.createCipher('AES-<mode>', key);
  953. * forge.cipher.createDecipher('AES-<mode>', key);
  954. *
  955. * Creates a deprecated AES cipher object. This object's mode will default to
  956. * CBC (cipher-block-chaining).
  957. *
  958. * The key and iv may be given as a string of bytes, an array of bytes, a
  959. * byte buffer, or an array of 32-bit words.
  960. *
  961. * @param options the options to use.
  962. * key the symmetric key to use.
  963. * output the buffer to write to.
  964. * decrypt true for decryption, false for encryption.
  965. * mode the cipher mode to use (default: 'CBC').
  966. *
  967. * @return the cipher.
  968. */
  969. function _createCipher(options) {
  970. options = options || {};
  971. var mode = (options.mode || 'CBC').toUpperCase();
  972. var algorithm = 'AES-' + mode;
  973. var cipher;
  974. if(options.decrypt) {
  975. cipher = forge.cipher.createDecipher(algorithm, options.key);
  976. } else {
  977. cipher = forge.cipher.createCipher(algorithm, options.key);
  978. }
  979. // backwards compatible start API
  980. var start = cipher.start;
  981. cipher.start = function(iv, options) {
  982. // backwards compatibility: support second arg as output buffer
  983. var output = null;
  984. if(options instanceof forge.util.ByteBuffer) {
  985. output = options;
  986. options = {};
  987. }
  988. options = options || {};
  989. options.output = output;
  990. options.iv = iv;
  991. start.call(cipher, options);
  992. };
  993. return cipher;
  994. }