simplest Hash algorithm Javascript


Requirements:

PHP function pack in Javascript
PHP function str_split in Javascript
PHP unpack function in Javascript

class TSHash {

  constructor(seed) {
    if (seed == undefined)
      seed = 0x11afec09
    this.result = this.seed = seed;
    this.chunks = [];
    this.end = "";
  }

  update(str) {
    if (str == '') return this;
    str = this.end + str;
    var strs = str_split(str, 4);
    var end = strs.pop();
    this.chunks = this.chunks.concat(strs);
    if (end.length == 4) {
      this.chunks.push(end);
      this.end = '';
    } else {
      this.end = end;
    }
    for (var si in this.chunks) {
      var s = this.chunks[si];
      var vv = unpack('l*', s)[1];
      this.result = this.result ^ vv;
      this.result = this.result ^ (vv >> 2);
    }
    return this;
  }

  digest() {
    if (this.end.length > 0) {
      var vv = 0;
      for (var i = this.end.length - 1; i >= 0; i--) {
        vv += Math.pow(256, i) * unpack('c*', this.end[i])[1];
      }
      this.result = this.result ^ vv;
      this.result = this.result ^ (vv >> 2);
    }

    return this;
  }

  toHex() {
    var result = pack('l*', this.result);
    var ret = "";
    for (var i = result.length - 1; i >= 0; i--) {
      var _ = unpack('H*', result[i])[1]
      ret += _.length == 1 ? '0' + _ : _;
    }
    return ret;
  }
}

Example:

Hash = new TSHash();

alert(Hash.update('bcdef').update('ghijklm1').digest().toHex());

Result:

14aae33b

Try it yourself

update new version:
https://jsfiddle.net/sans_amour/ng74y9re/1/

Read more: this method in PHP language: simplest Hash algorithm PHP

Leave a Reply