AES.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const TextEncoder = require("util").TextEncoder;
  2. const TextDecoder = require("util").TextDecoder;
  3. const aesjs = require('aes-js');
  4. class AES {
  5. static decryptIge(cipherText, key, iv) {
  6. let iv1 = iv.slice(0, Math.floor(iv.length / 2));
  7. let iv2 = iv.slice(Math.floor(iv.length / 2));
  8. let plainText = new Array(cipherText.length).fill(0);
  9. let aes = new aesjs.AES(key);
  10. let blocksCount = Math.floor(plainText.length / 16);
  11. let cipherTextBlock = new Array(16).fill(0);
  12. for (let blockIndex = 0; blockIndex < blocksCount; blockIndex++) {
  13. for (let i = 0; i < 16; i++) {
  14. cipherTextBlock[i] = cipherText[blockIndex * 16 + i] ^ iv2[i];
  15. }
  16. let plainTextBlock = aes.decrypt(cipherTextBlock);
  17. for (let i = 0; i < 16; i++) {
  18. plainTextBlock[i] ^= iv1[i];
  19. }
  20. iv1 = cipherText.slice(blockIndex * 16, blockIndex * 16 + 16);
  21. iv2 = plainTextBlock.slice(0, 16);
  22. plainText = new Uint8Array([
  23. ...plainText.slice(0, blockIndex * 16),
  24. ...plainTextBlock.slice(0, 16),
  25. ...plainText.slice(blockIndex * 16 + 16)
  26. ]);
  27. }
  28. return plainText;
  29. }
  30. static encryptIge(plainText, key, iv) {
  31. if (plainText.length % 16 !== 0) {
  32. let padding = new Uint8Array(16 - plainText.length % 16);
  33. plainText = new Uint8Array([
  34. ...plainText,
  35. ...padding,
  36. ]);
  37. }
  38. let iv1 = iv.slice(0, Math.floor(iv.length / 2));
  39. let iv2 = iv.slice(Math.floor(iv.length / 2));
  40. let aes = new aesjs.AES(key);
  41. let blocksCount = Math.floor(plainText.length / 16);
  42. let cipherText = new Array(plainText.length).fill(0);
  43. for (let blockIndex = 0; blockIndex < blocksCount; blockIndex++) {
  44. let plainTextBlock = plainText.slice(blockIndex * 16, blockIndex * 16 + 16);
  45. for (let i = 0; i < 16; i++) {
  46. plainTextBlock[i] ^= iv1[i];
  47. }
  48. let cipherTextBlock = aes.encrypt(plainTextBlock);
  49. for (let i = 0; i < 16; i++) {
  50. cipherTextBlock[i] ^= iv2[i];
  51. }
  52. iv1 = cipherTextBlock.slice(0, 16);
  53. iv2 = plainText.slice(blockIndex * 16, blockIndex * 16 + 16);
  54. cipherText = new Uint8Array([
  55. ...cipherText.slice(0, blockIndex * 16),
  56. ...cipherTextBlock.slice(0, 16),
  57. ...cipherText.slice(blockIndex * 16 + 16)
  58. ]);
  59. }
  60. return cipherText;
  61. }
  62. }
  63. exports.AES = AES;