tjwebb / fnv-plus

Javascript FNV-1a Hash Algorithm (up to 1024 bit) implementation. Based on:
http://tools.ietf.org/html/draft-eastlake-fnv-06
85 stars 13 forks source link

fnv-plus

NPM version Build status

Javascript FNV-1a Hashing Algorithm up to 1024 bits, with highly optimized 32bit and 52bit implementations.

Concept

The FNV-1a hash algorithm, often simply called "fnv", disperses hashes throughout the n-bit hash space with very good dispersion and is very fast.

Use this module to generate unique hash/checksum values for Javascript strings or objects. Note: The FNV-1a algorithm is not even remotely suitable as a cryptographic pseudo-random generator, and should not be used to secure any thing for any reason. It is designed for uniqueness, not randomness.

Why fnv-plus?
New in 1.3.x
New in 1.2.x

Install

$ npm install fnv-plus --save

Usage

var fnv = require('fnv-plus'),
    astring = 'hello world',
    ahash52 = fnv.hash(astring),        // 52-bit hash by default
    ahash64 = fnv.hash(astring, 64);    // 64-bit hash specified

console.log(ahash52.hex() == 'a65e7023cd59e');    //true
console.log(ahash52.str() == 'stglysbf6m');       //true
console.log(ahash52.dec() == '2926792616498590'); //true

console.log(ahash64.hex() == '779a65e7023cd2e7');     //true
console.log(ahash64.str() == '1th7cxzlyc0dj');        //true
console.log(ahash64.dec() == '8618312879776256743');  //true

// fast variants
console.log(fnv.fast1a32hex(astring) == 'd58b3fa7');      //true
console.log(fnv.fast1a52hex(astring) == 'a65e7023cd59e'); //true

fnv.seed('foobar testseed');
console.log(fnv.hash(astring, 64).hex() == ahash64.hex()); // false
// ^^ because the default seed is not 'foobar testseed'

API

fnv.hash(string, bitlength)

fnv.seed(string)

fnv.useUTF8(bool)

FnvHash.str()

Returns the hashed value as an ascii string

FnvHash.hex()

Returns the hashed value as a hexadecimal string

FnvHash.dec()

Returns the hashed value as a decimal string

Fast variants

This functions runs faster because they have no lib-overhead (see benchmarks for more info). They always compute 1a version of hashes and always use default seed. Directly returns hash values (not FnvHash object).

fnv.fast1a32(string)

fnv.fast1a32hex(string)

fnv.fast1a52(string)

fnv.fast1a52hex(string)

fnv.fast1a64(string)

fnv.fast1a32utf(string)

fnv.fast1a32hexutf(string)

fnv.fast1a52utf(string)

fnv.fast1a52hexutf(string)

fnv.fast1a64utf(string)

License

MIT