djb2函数中碰撞的可能性是多少?

时间:2015-06-25 13:17:42

标签: javascript hash cryptography hashcode

我正在尝试使用djb2哈希函数为

这样的字符串生成唯一的id

"114.143.227.82Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"

使用此算法在javascript中给出的碰撞可能性有多大。

String.prototype.hashCode = function(){ var hash = 5381; if (this.length === 0) return hash; for (var i = 0; i < this.length; i++) { var character = this.charCodeAt(i); hash = (( hash << 5 ) + hash ) ^ character; } return hash; }

用法:

var hash = new String("114.143.227.82"+navigator.userAgent).hashCode();

alert(hash);

参考:

http://www.cse.yorku.ca/~oz/hash.html

对于上面的字符串,我得到-ve整数值。如何为这些类型的字符串返回+ ve整数?

1 个答案:

答案 0 :(得分:0)

我在修改上述代码后得到了解决方案。

String.prototype.hashCode = function(){ var hash = 5381; if (this.length === 0) return hash; for (var i = 0; i < this.length; i++) { var character = this.charCodeAt(i);
hash = hash * 33 ^character; } return hash >>>0; }