All files / node-unzipper/lib Decrypt.js

100% Statements 68/68
100% Branches 16/16
100% Functions 7/7
100% Lines 68/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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