Decrypt.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const Int64 = require("node-int64");
  2. let Stream = require("stream");
  3. // Backwards compatibility for node versions < 8
  4. if (!Stream.Writable || !Stream.Writable.prototype.destroy)
  5. Stream = require("readable-stream");
  6. let table;
  7. function generateTable() {
  8. const poly = 0xEDB88320;
  9. let c, n, k;
  10. table = [];
  11. for (n = 0; n < 256; n++) {
  12. c = n;
  13. for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >>> 1) : (c = c >>> 1);
  14. table[n] = c >>> 0;
  15. }
  16. }
  17. function crc(ch, crc) {
  18. if (!table) generateTable();
  19. if (ch.charCodeAt) ch = ch.charCodeAt(0);
  20. const l = (crc.readUInt32BE() >> 8) & 0xffffff;
  21. const r = table[(crc.readUInt32BE() ^ (ch >>> 0)) & 0xff];
  22. return (l ^ r) >>> 0;
  23. }
  24. function multiply(a, b) {
  25. const ah = (a >> 16) & 0xffff;
  26. const al = a & 0xffff;
  27. const bh = (b >> 16) & 0xffff;
  28. const bl = b & 0xffff;
  29. const high = (ah * bl + al * bh) & 0xffff;
  30. return ((high << 16) >>> 0) + al * bl;
  31. }
  32. function Decrypt() {
  33. if (!(this instanceof Decrypt)) return new Decrypt();
  34. this.key0 = Buffer.allocUnsafe(4);
  35. this.key1 = Buffer.allocUnsafe(4);
  36. this.key2 = Buffer.allocUnsafe(4);
  37. this.key0.writeUInt32BE(0x12345678, 0);
  38. this.key1.writeUInt32BE(0x23456789, 0);
  39. this.key2.writeUInt32BE(0x34567890, 0);
  40. }
  41. Decrypt.prototype.update = function (h) {
  42. this.key0.writeUInt32BE(crc(h, this.key0));
  43. this.key1.writeUInt32BE(
  44. ((this.key0.readUInt32BE() & 0xff & 0xFFFFFFFF) +
  45. this.key1.readUInt32BE()) >>> 0
  46. );
  47. const x = new Int64(
  48. (multiply(this.key1.readUInt32BE(), 134775813) + 1) & 0xFFFFFFFF
  49. );
  50. const b = Buffer.alloc(8);
  51. x.copy(b, 0);
  52. b.copy(this.key1, 0, 4, 8);
  53. this.key2.writeUInt32BE(
  54. crc(((this.key1.readUInt32BE() >> 24) & 0xff) >>> 0, this.key2)
  55. );
  56. };
  57. Decrypt.prototype.decryptByte = function (c) {
  58. const k = (this.key2.readUInt32BE() | 2) >>> 0;
  59. c = c ^ ((multiply(k, (k ^ 1 >>> 0)) >> 8) & 0xff);
  60. this.update(c);
  61. return c;
  62. };
  63. Decrypt.prototype.stream = function () {
  64. const stream = Stream.Transform(),
  65. self = this;
  66. stream._transform = function (d, e, cb) {
  67. for (let i = 0; i < d.length; i++) {
  68. d[i] = self.decryptByte(d[i]);
  69. }
  70. this.push(d);
  71. cb();
  72. };
  73. return stream;
  74. };
  75. module.exports = Decrypt;