JavaScript的简单(非安全)散列函数? [英] Simple (non-secure) hash function for JavaScript?

查看:78
本文介绍了JavaScript的简单(非安全)散列函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:


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

我没有自己验证,但你可以看看这个 Java的String.hashCode()方法的JavaScript实现。看起来很合理。


使用此原型,您可以简单地调用 .hashCode()在任何字符串上,例如some string.hashCode(),并且接收一个数字哈希码(更具体地说,是一个Java等价物),例如1395333309。
blockquote>

  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&散列; //转换为32位整数
}
返回散列;
}


Possible Duplicate:
Generate a Hash from string in 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.)

解决方案

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

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.

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;
}

这篇关于JavaScript的简单(非安全)散列函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆