2

I need to generate a hash key with two inputs (strings) ex: inputA != inputB is true

key1 = hash_method(inputA, inputB);

key2 = hash_method(inputB, inputA);

and the condition

key1 === key2 is true.

I will be needing for js but If somebody can help me with java or ruby I can traduce it. Or you have some plugin or library for js would be great. I dont need that the key will be very secure but I need that this will be only

thank you

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
Raul Benitez
  • 35
  • 1
  • 7

3 Answers3

3

I'd just XOR the hashes of the strings. It's the common way to create a hash on fields of an object. XOR is commutative, so your condition should be true.

function hash_method(inputAHash, inputBHash) { return inputAHash ^ inputBHash };

Links:

This answer gives info how to compute a good hash code on a string (to compute hashes from inputA and inputB).

How to create hash codes based on fields of an object (it's a Java tutorial but the same would apply in JS).

Community
  • 1
  • 1
david a.
  • 5,283
  • 22
  • 24
3

Assuming that the hash code generation used in Java for string is good enough, it is quite trivial to implement it in Javascript. If you want a hash code built over multiple strings, where the order of the strings is irrelevant, you can combine the hash code for each string with xor.

The following Javascript function can be invoked with one or multiple arguments:

function hash() {

    var h=0, i=0;

    if(hash.arguments.length == 1) {
        for(i=0; i<hash.arguments[0].length; i++) {
            h = (h * 31 + hash.arguments[0].charCodeAt(i)) & 0xffffffff;
        }
    }
    else {
        for(i in hash.arguments) {
            h ^= hash(hash.arguments[i]);
        }
    }

    return h;
}

Note that the resulting range of this function is unsigned ([0, 2^32>) and not signed ([-2^31, 2^31>) as Java's String#hashCode().

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
0

my Final solution:

var hash = function (params)  {
        var h=0, i=0;
        if(typeof (params) === "string") {
            for(i=0; i<params.length; i++) {
                h = (h * 31 + params.charCodeAt(i)) & 0xffffffff;
            }
        }
        else if( params instanceof Array) {
            for(i in params) {
                h ^= hash(params[i]);
            }
        }
        return h;
};

var a1 = "pc-1"; var a2 = "router-2";
var params1 = [a1, a2];
hash(params1); //result 6720633
var params2 = [a2,a1];
hash(params2); //result 6720633
Raul Benitez
  • 35
  • 1
  • 7