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

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

问题描述

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

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

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.)

推荐答案

这个我自己没有验证过,你可以看看这个 Java 的 String.hashCode() 方法的 JavaScript 实现.看起来相当短.

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

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

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天全站免登陆