JS散列函数应始终为特定字符串返回相同的散列

时间:2017-01-14 11:06:06

标签: javascript hash

我有这样的功能:

var hashString = function (str) {
            var mask = '';
            if (str.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
            if (str.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            if (str.indexOf('#') > -1) mask += '0123456789';
            if (str.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
            var result = '';
            for (var i = 8; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
            return result;
        }

如何让它始终返回特定字符串的相同哈希值?

1 个答案:

答案 0 :(得分:0)

此函数将始终为特定字符串返回相同的哈希值:

 /**
 * Calculate a 32 bit FNV-1a hash
 * Found here: https://gist.github.com/vaiorabbit/5657561
 * Ref.: http://isthe.com/chongo/tech/comp/fnv/
 *
 * @param {string} str the input value
 * @param {boolean} [asString=false] set to true to return the hash value as 
 *     8-digit hex string instead of an integer
 * @param {integer} [seed] optionally pass the hash of the previous chunk
 * @returns {integer | string}
 */
function hashFnv32a(str, asString, seed) {
    /*jshint bitwise:false */
    var i, l,
        hval = (seed === undefined) ? 0x811c9dc5 : seed;

    for (i = 0, l = str.length; i < l; i++) {
        hval ^= str.charCodeAt(i);
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }
    if (asString) {
        // Convert to 8 digit hex string
        return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
    }
    return hval >>> 0;
}

Generate a Hash from string in Javascript/jQuery