Decrypt.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. var bigInt = require('big-integer');
  2. var Stream = require('stream');
  3. // Backwards compatibility for node versions < 8
  4. if (!Stream.Writable || !Stream.Writable.prototype.destroy)
  5. Stream = require('readable-stream');
  6. var table;
  7. function generateTable() {
  8. var poly = 0xEDB88320,c,n,k;
  9. table = [];
  10. for (n = 0; n < 256; n++) {
  11. c = n;
  12. for (k = 0; k < 8; k++)
  13. c = (c & 1) ? poly ^ (c >>> 1) : c = c >>> 1;
  14. table[n] = c >>> 0;
  15. }
  16. }
  17. function crc(ch,crc) {
  18. if (!table)
  19. generateTable();
  20. if (ch.charCodeAt)
  21. ch = ch.charCodeAt(0);
  22. return (bigInt(crc).shiftRight(8).and(0xffffff)).xor(table[bigInt(crc).xor(ch).and(0xff)]).value;
  23. }
  24. function Decrypt() {
  25. if (!(this instanceof Decrypt))
  26. return new Decrypt();
  27. this.key0 = 305419896;
  28. this.key1 = 591751049;
  29. this.key2 = 878082192;
  30. }
  31. Decrypt.prototype.update = function(h) {
  32. this.key0 = crc(h,this.key0);
  33. this.key1 = bigInt(this.key0).and(255).and(4294967295).add(this.key1)
  34. this.key1 = bigInt(this.key1).multiply(134775813).add(1).and(4294967295).value;
  35. this.key2 = crc(bigInt(this.key1).shiftRight(24).and(255), this.key2);
  36. }
  37. Decrypt.prototype.decryptByte = function(c) {
  38. var k = bigInt(this.key2).or(2);
  39. c = c ^ bigInt(k).multiply(bigInt(k^1)).shiftRight(8).and(255);
  40. this.update(c);
  41. return c;
  42. };
  43. Decrypt.prototype.stream = function() {
  44. var stream = Stream.Transform(),
  45. self = this;
  46. stream._transform = function(d,e,cb) {
  47. for (var i = 0; i<d.length;i++) {
  48. d[i] = self.decryptByte(d[i]);
  49. }
  50. this.push(d);
  51. cb();
  52. };
  53. return stream;
  54. };
  55. module.exports = Decrypt;