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.

410 lines
12 KiB

4 years ago
  1. /**
  2. * RC2 implementation.
  3. *
  4. * @author Stefan Siegl
  5. *
  6. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  7. *
  8. * Information on the RC2 cipher is available from RFC #2268,
  9. * http://www.ietf.org/rfc/rfc2268.txt
  10. */
  11. var forge = require('./forge');
  12. require('./util');
  13. var piTable = [
  14. 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
  15. 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
  16. 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
  17. 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
  18. 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
  19. 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
  20. 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
  21. 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
  22. 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
  23. 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
  24. 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
  25. 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
  26. 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
  27. 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
  28. 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
  29. 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad
  30. ];
  31. var s = [1, 2, 3, 5];
  32. /**
  33. * Rotate a word left by given number of bits.
  34. *
  35. * Bits that are shifted out on the left are put back in on the right
  36. * hand side.
  37. *
  38. * @param word The word to shift left.
  39. * @param bits The number of bits to shift by.
  40. * @return The rotated word.
  41. */
  42. var rol = function(word, bits) {
  43. return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));
  44. };
  45. /**
  46. * Rotate a word right by given number of bits.
  47. *
  48. * Bits that are shifted out on the right are put back in on the left
  49. * hand side.
  50. *
  51. * @param word The word to shift right.
  52. * @param bits The number of bits to shift by.
  53. * @return The rotated word.
  54. */
  55. var ror = function(word, bits) {
  56. return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);
  57. };
  58. /* RC2 API */
  59. module.exports = forge.rc2 = forge.rc2 || {};
  60. /**
  61. * Perform RC2 key expansion as per RFC #2268, section 2.
  62. *
  63. * @param key variable-length user key (between 1 and 128 bytes)
  64. * @param effKeyBits number of effective key bits (default: 128)
  65. * @return the expanded RC2 key (ByteBuffer of 128 bytes)
  66. */
  67. forge.rc2.expandKey = function(key, effKeyBits) {
  68. if(typeof key === 'string') {
  69. key = forge.util.createBuffer(key);
  70. }
  71. effKeyBits = effKeyBits || 128;
  72. /* introduce variables that match the names used in RFC #2268 */
  73. var L = key;
  74. var T = key.length();
  75. var T1 = effKeyBits;
  76. var T8 = Math.ceil(T1 / 8);
  77. var TM = 0xff >> (T1 & 0x07);
  78. var i;
  79. for(i = T; i < 128; i++) {
  80. L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);
  81. }
  82. L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);
  83. for(i = 127 - T8; i >= 0; i--) {
  84. L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);
  85. }
  86. return L;
  87. };
  88. /**
  89. * Creates a RC2 cipher object.
  90. *
  91. * @param key the symmetric key to use (as base for key generation).
  92. * @param bits the number of effective key bits.
  93. * @param encrypt false for decryption, true for encryption.
  94. *
  95. * @return the cipher.
  96. */
  97. var createCipher = function(key, bits, encrypt) {
  98. var _finish = false, _input = null, _output = null, _iv = null;
  99. var mixRound, mashRound;
  100. var i, j, K = [];
  101. /* Expand key and fill into K[] Array */
  102. key = forge.rc2.expandKey(key, bits);
  103. for(i = 0; i < 64; i++) {
  104. K.push(key.getInt16Le());
  105. }
  106. if(encrypt) {
  107. /**
  108. * Perform one mixing round "in place".
  109. *
  110. * @param R Array of four words to perform mixing on.
  111. */
  112. mixRound = function(R) {
  113. for(i = 0; i < 4; i++) {
  114. R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +
  115. ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
  116. R[i] = rol(R[i], s[i]);
  117. j++;
  118. }
  119. };
  120. /**
  121. * Perform one mashing round "in place".
  122. *
  123. * @param R Array of four words to perform mashing on.
  124. */
  125. mashRound = function(R) {
  126. for(i = 0; i < 4; i++) {
  127. R[i] += K[R[(i + 3) % 4] & 63];
  128. }
  129. };
  130. } else {
  131. /**
  132. * Perform one r-mixing round "in place".
  133. *
  134. * @param R Array of four words to perform mixing on.
  135. */
  136. mixRound = function(R) {
  137. for(i = 3; i >= 0; i--) {
  138. R[i] = ror(R[i], s[i]);
  139. R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +
  140. ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
  141. j--;
  142. }
  143. };
  144. /**
  145. * Perform one r-mashing round "in place".
  146. *
  147. * @param R Array of four words to perform mashing on.
  148. */
  149. mashRound = function(R) {
  150. for(i = 3; i >= 0; i--) {
  151. R[i] -= K[R[(i + 3) % 4] & 63];
  152. }
  153. };
  154. }
  155. /**
  156. * Run the specified cipher execution plan.
  157. *
  158. * This function takes four words from the input buffer, applies the IV on
  159. * it (if requested) and runs the provided execution plan.
  160. *
  161. * The plan must be put together in form of a array of arrays. Where the
  162. * outer one is simply a list of steps to perform and the inner one needs
  163. * to have two elements: the first one telling how many rounds to perform,
  164. * the second one telling what to do (i.e. the function to call).
  165. *
  166. * @param {Array} plan The plan to execute.
  167. */
  168. var runPlan = function(plan) {
  169. var R = [];
  170. /* Get data from input buffer and fill the four words into R */
  171. for(i = 0; i < 4; i++) {
  172. var val = _input.getInt16Le();
  173. if(_iv !== null) {
  174. if(encrypt) {
  175. /* We're encrypting, apply the IV first. */
  176. val ^= _iv.getInt16Le();
  177. } else {
  178. /* We're decryption, keep cipher text for next block. */
  179. _iv.putInt16Le(val);
  180. }
  181. }
  182. R.push(val & 0xffff);
  183. }
  184. /* Reset global "j" variable as per spec. */
  185. j = encrypt ? 0 : 63;
  186. /* Run execution plan. */
  187. for(var ptr = 0; ptr < plan.length; ptr++) {
  188. for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {
  189. plan[ptr][1](R);
  190. }
  191. }
  192. /* Write back result to output buffer. */
  193. for(i = 0; i < 4; i++) {
  194. if(_iv !== null) {
  195. if(encrypt) {
  196. /* We're encrypting in CBC-mode, feed back encrypted bytes into
  197. IV buffer to carry it forward to next block. */
  198. _iv.putInt16Le(R[i]);
  199. } else {
  200. R[i] ^= _iv.getInt16Le();
  201. }
  202. }
  203. _output.putInt16Le(R[i]);
  204. }
  205. };
  206. /* Create cipher object */
  207. var cipher = null;
  208. cipher = {
  209. /**
  210. * Starts or restarts the encryption or decryption process, whichever
  211. * was previously configured.
  212. *
  213. * To use the cipher in CBC mode, iv may be given either as a string
  214. * of bytes, or as a byte buffer. For ECB mode, give null as iv.
  215. *
  216. * @param iv the initialization vector to use, null for ECB mode.
  217. * @param output the output the buffer to write to, null to create one.
  218. */
  219. start: function(iv, output) {
  220. if(iv) {
  221. /* CBC mode */
  222. if(typeof iv === 'string') {
  223. iv = forge.util.createBuffer(iv);
  224. }
  225. }
  226. _finish = false;
  227. _input = forge.util.createBuffer();
  228. _output = output || new forge.util.createBuffer();
  229. _iv = iv;
  230. cipher.output = _output;
  231. },
  232. /**
  233. * Updates the next block.
  234. *
  235. * @param input the buffer to read from.
  236. */
  237. update: function(input) {
  238. if(!_finish) {
  239. // not finishing, so fill the input buffer with more input
  240. _input.putBuffer(input);
  241. }
  242. while(_input.length() >= 8) {
  243. runPlan([
  244. [ 5, mixRound ],
  245. [ 1, mashRound ],
  246. [ 6, mixRound ],
  247. [ 1, mashRound ],
  248. [ 5, mixRound ]
  249. ]);
  250. }
  251. },
  252. /**
  253. * Finishes encrypting or decrypting.
  254. *
  255. * @param pad a padding function to use, null for PKCS#7 padding,
  256. * signature(blockSize, buffer, decrypt).
  257. *
  258. * @return true if successful, false on error.
  259. */
  260. finish: function(pad) {
  261. var rval = true;
  262. if(encrypt) {
  263. if(pad) {
  264. rval = pad(8, _input, !encrypt);
  265. } else {
  266. // add PKCS#7 padding to block (each pad byte is the
  267. // value of the number of pad bytes)
  268. var padding = (_input.length() === 8) ? 8 : (8 - _input.length());
  269. _input.fillWithByte(padding, padding);
  270. }
  271. }
  272. if(rval) {
  273. // do final update
  274. _finish = true;
  275. cipher.update();
  276. }
  277. if(!encrypt) {
  278. // check for error: input data not a multiple of block size
  279. rval = (_input.length() === 0);
  280. if(rval) {
  281. if(pad) {
  282. rval = pad(8, _output, !encrypt);
  283. } else {
  284. // ensure padding byte count is valid
  285. var len = _output.length();
  286. var count = _output.at(len - 1);
  287. if(count > len) {
  288. rval = false;
  289. } else {
  290. // trim off padding bytes
  291. _output.truncate(count);
  292. }
  293. }
  294. }
  295. }
  296. return rval;
  297. }
  298. };
  299. return cipher;
  300. };
  301. /**
  302. * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the
  303. * given symmetric key. The output will be stored in the 'output' member
  304. * of the returned cipher.
  305. *
  306. * The key and iv may be given as a string of bytes or a byte buffer.
  307. * The cipher is initialized to use 128 effective key bits.
  308. *
  309. * @param key the symmetric key to use.
  310. * @param iv the initialization vector to use.
  311. * @param output the buffer to write to, null to create one.
  312. *
  313. * @return the cipher.
  314. */
  315. forge.rc2.startEncrypting = function(key, iv, output) {
  316. var cipher = forge.rc2.createEncryptionCipher(key, 128);
  317. cipher.start(iv, output);
  318. return cipher;
  319. };
  320. /**
  321. * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the
  322. * given symmetric key.
  323. *
  324. * The key may be given as a string of bytes or a byte buffer.
  325. *
  326. * To start encrypting call start() on the cipher with an iv and optional
  327. * output buffer.
  328. *
  329. * @param key the symmetric key to use.
  330. *
  331. * @return the cipher.
  332. */
  333. forge.rc2.createEncryptionCipher = function(key, bits) {
  334. return createCipher(key, bits, true);
  335. };
  336. /**
  337. * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the
  338. * given symmetric key. The output will be stored in the 'output' member
  339. * of the returned cipher.
  340. *
  341. * The key and iv may be given as a string of bytes or a byte buffer.
  342. * The cipher is initialized to use 128 effective key bits.
  343. *
  344. * @param key the symmetric key to use.
  345. * @param iv the initialization vector to use.
  346. * @param output the buffer to write to, null to create one.
  347. *
  348. * @return the cipher.
  349. */
  350. forge.rc2.startDecrypting = function(key, iv, output) {
  351. var cipher = forge.rc2.createDecryptionCipher(key, 128);
  352. cipher.start(iv, output);
  353. return cipher;
  354. };
  355. /**
  356. * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the
  357. * given symmetric key.
  358. *
  359. * The key may be given as a string of bytes or a byte buffer.
  360. *
  361. * To start decrypting call start() on the cipher with an iv and optional
  362. * output buffer.
  363. *
  364. * @param key the symmetric key to use.
  365. *
  366. * @return the cipher.
  367. */
  368. forge.rc2.createDecryptionCipher = function(key, bits) {
  369. return createCipher(key, bits, false);
  370. };