JavaScript 的简单(非安全)哈希函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6122571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:20:24  来源:igfitidea点击:

Simple (non-secure) hash function for JavaScript?

javascripthashmd5sha1

提问by mjs

Possible Duplicate:
Generate a Hash from string in Javascript/jQuery

可能的重复:
从 Javascript/jQuery 中的字符串生成哈希

Can anyone suggest a simple (i.e. tens of lines of code, not hundreds of lines) hash function written in (browser-compatible) JavaScript? Ideally I'd like something that, when passed a string as input, produces something similar to the 32 character hexadecimal string that's the typical output of MD5, SHA1, etc. It doesn't have to be cryptographically secure, just reasonably resistant to collisions. (My initial use case is URLs, but I'll probably want to use it on other strings in the future.)

谁能建议一个用(浏览器兼容的)JavaScript 编写的简单(即数十行代码,而不是数百行)散列函数?理想情况下,我想要一些东西,当将字符串作为输入传递时,会产生类似于 32 个字符的十六进制字符串的东西,这是 MD5、SHA1 等的典型输出。它不必是加密安全的,只需合理地抵抗冲突. (我最初的用例是 URL,但我将来可能想在其他字符串上使用它。)

回答by Barak

I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.

我自己没有验证这一点,但您可以查看Java 的 String.hashCode() 方法的 JavaScript 实现。似乎相当短。

With this prototype you can simply call .hashCode()on any string, e.g. "some string".hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

使用这个原型,您可以简单地调用.hashCode()任何字符串,例如"some string".hashCode(),并接收数字哈希代码(更具体地说,Java 等效代码),例如 1395333309。

String.prototype.hashCode = function() {
    var hash = 0;
    if (this.length == 0) {
        return hash;
    }
    for (var i = 0; i < this.length; i++) {
        var char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

回答by silex

There are many realizations of hash functions written in JS. For example:

有很多用 JS 编写的哈希函数的实现。例如:

If you don't need security, you can also use base64 which is not hash-function, has not fixed output and could be simply decoded by user, but looks more lightweight and could be used for hide values: http://www.webtoolkit.info/javascript-base64.html

如果你不需要安全性,你也可以使用 base64,它不是哈希函数,没有固定输出,可以简单地由用户解码,但看起来更轻量级,可以用于隐藏值:http://www。 webtoolkit.info/javascript-base64.html

回答by Stefan Filip

Check out these implementations

查看这些实现

回答by Tom

This article explains simple hash functionsin some detail and provides some sample code (in C) that is pretty straighforward. Looks like Bob Jenkins' hash functioncould be appropriate for your needs (this Dr Dobbs articlehas more details and a survey of other hash functions, both of which could be helpful).

本文详细解释了简单的哈希函数,并提供了一些非常直接的示例代码(C 语言)。看起来Bob Jenkins 的散列函数可能适合您的需求(这篇Dobbs 博士文章有更多详细信息和对其他散列函数的调查,两者都可能有帮助)。

回答by Fordi

Simple object hasher:

简单的对象哈希器:

(function () {
    Number.prototype.toHex = function () {
        var ret = ((this<0?0x8:0)+((this >> 28) & 0x7)).toString(16) + (this & 0xfffffff).toString(16);
        while (ret.length < 8) ret = '0'+ret;
        return ret;
    };
    Object.hashCode = function hashCode(o, l) {
        l = l || 2;
        var i, c, r = [];
        for (i=0; i<l; i++)
            r.push(i*268803292);
        function stringify(o) {
            var i,r;
            if (o === null) return 'n';
            if (o === true) return 't';
            if (o === false) return 'f';
            if (o instanceof Date) return 'd:'+(0+o);
            i=typeof o;
            if (i === 'string') return 's:'+o.replace(/([\\;])/g,'\');
            if (i === 'number') return 'n:'+o;
            if (o instanceof Function) return 'm:'+o.toString().replace(/([\\;])/g,'\');
            if (o instanceof Array) {
                r=[];
                for (i=0; i<o.length; i++) 
                    r.push(stringify(o[i]));
                return 'a:'+r.join(';');
            }
            r=[];
            for (i in o) {
                r.push(i+':'+stringify(o[i]))
            }
            return 'o:'+r.join(';');
        }
        o = stringify(o);
        for (i=0; i<o.length; i++) {
            for (c=0; c<r.length; c++) {
                r[c] = (r[c] << 13)-(r[c] >> 19);
                r[c] += o.charCodeAt(i) << (r[c] % 24);
                r[c] = r[c] & r[c];
            }
        }
        for (i=0; i<r.length; i++) {
            r[i] = r[i].toHex();
        }
        return r.join('');
    }
}());

The meat here is the stringifier, which simply converts any object into a unique string. hashCode then runs over the object, hashing together the characters of the stringified object.

这里的主要内容是 stringifier,它只是将任何对象转换为唯一的字符串。hashCode 然后在对象上运行,将字符串化对象的字符散列在一起。

For extra points, export the stringifier and create a parser.

对于额外的点,导出 stringifier 并创建一个解析器。

回答by Sergey Shuchkin

// Simple but unreliable function to create string hash by Sergey.Shuchkin [t] gmail.com
// alert( strhash('http://www.w3schools.com/js/default.asp') ); // 6mn6tf7st333r2q4o134o58888888888
function strhash( str ) {
    if (str.length % 32 > 0) str += Array(33 - str.length % 32).join("z");
    var hash = '', bytes = [], i = j = k = a = 0, dict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','1','2','3','4','5','6','7','8','9'];
    for (i = 0; i < str.length; i++ ) {
        ch = str.charCodeAt(i);
        bytes[j++] = (ch < 127) ? ch & 0xFF : 127;
    }
    var chunk_len = Math.ceil(bytes.length / 32);   
    for (i=0; i<bytes.length; i++) {
        j += bytes[i];
        k++;
        if ((k == chunk_len) || (i == bytes.length-1)) {
            a = Math.floor( j / k );
            if (a < 32)
                hash += '0';
            else if (a > 126)
                hash += 'z';
            else
                hash += dict[  Math.floor( (a-32) / 2.76) ];
            j = k = 0;
        }
    }
    return hash;
}

回答by jsalonen

Check out this MD5 implementation for JavaScript. Its BSD Licensed and really easy to use. Example:

查看此JavaScript 的 MD5 实现。它的 BSD 许可并且非常易于使用。例子:

md5 = hex_md5("message to digest")