Air In
Air In

Reputation: 975

PRNG-like seeded hash function

I want two clients using the same "seed" to generate the same number by inputting a time stamp or long number, returning a float like using random().

For example w/ the function: hasher(String seed, long input);

 hasher("StackOverflow", 1000000010); //returns 0.57217329503213..
 hasher("StackOverflow", 1000000010); //returns 0.57217329503213...
 hasher("StackOverflowz", 1000000010); //returns 0.15689784654554...
 hasher("StackOverflow", 97494849465); //returns 0.456944151561...

It really isn't supposed to be secure or private, but just random enough. I figured I could use bit manipulation, but I'm by no means an expert at either hashing or bit manipulation.

I realize seed is pretty much redundant as combining seed and input, but I suppose it'd help to know the best way to implement a seed in it without compromising reliability. Any ideas?

Thanks.

Upvotes: 1

Views: 438

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94038

I made a small implementation, but beware that JavaScript is far from my primary language. The code requires CryptoJS for the hash functionality.

function hasher(a, b) {
    hash = fromHex(CryptoJS.enc.Hex.stringify(CryptoJS.SHA256(a + b)));    
    // warning: only about 32 bit precision
    hashAsDouble = intFromBytes(hash.slice(0, 4)) * (1.0 / 4294967296.0);
    return hashAsDouble;
}

function fromHex(hex) {
    a = [];
    for (var i = 0; i < hex.length; i += 2) {
        a.push("0x" + hex.substr(i, 2));
    }
    return a;
}

function intFromBytes(x) {
    if (x.length != 4) {
        return null;
    }

    var val = 0;
    for (var i = 0; i < x.length; i++) {
        val = val << 8;
        val = val + (x[i] & 0xFF);
    }
    return toUint32(val);
}

function modulo(a, b) {
    return a - Math.floor(a / b) * b;
}

function toUint32(x) {
    return modulo(toInteger(x), Math.pow(2, 32));
}

function toInteger(x) {
    x = Number(x);
    return x < 0 ? Math.ceil(x) : Math.floor(x);
}

Upvotes: 1

Related Questions