我需要将字符串转换为某种形式的哈希。这在JavaScript中是可能的吗?

我没有使用服务器端语言,所以我不能这样做。


当前回答

String.prototype.hashCode=函数(){var散列=0,i、 chr;如果(this.length==0)返回哈希;对于(i=0;i<this.length;i++){chr=this.charCodeAt(i);哈希=((哈希<<5)-哈希)+chr;哈希|=0;//转换为32位整数}返回哈希;}const str='收入'console.log(str,str.hashCode())

来源

其他回答

我有点惊讶,还没有人谈论新的SubtleCryptoAPI。

要从字符串中获取哈希,可以使用suble.desumest方法:

函数getHash(str,algo=“SHA-256”){let strBuf=newTextEncoder().encode(str);return crypto.define.digest(算法,strBuf).then(哈希=>{window.hash=哈希;//这里hash是arrayBuffer,//所以我们将其转换为十六进制版本let result=“”;const view=新数据视图(哈希);for(设i=0;i<hash.byteLength;i+=4){result+=('000000000'+view.getUint32(i).toString(16)).sslice(-8);}返回结果;});}getHash('hello world').then(哈希=>{console.log(哈希);});

基于ES6中接受的答案。更小,可维护,可在现代浏览器中使用。

函数hashCode(str){return str.split(“”).reduce((prevHash,currVal)=>(((prevHash<<5)-previvHash)+currVal.charCodeAt(0))|0,0);}//测试console.log(“hashCode(\“Hello!\”):“,hashCode('Hello!'));

编辑(2019-11-04):

单线箭头功能版本:

consthashCode=s=>s.split(“”).reduce((a,b)=>(((a<<5)-a)+b.charCodeAt(0))|0,0)//测试console.log(hashCode(“您好!”))

EDIT

根据我的jsperf测试,公认的答案实际上更快:http://jsperf.com/hashcodelordvlad

原始的,原始的

如果有人感兴趣,这里有一个改进的(更快的)版本,它将在缺少reduce数组功能的旧浏览器上失败。

hashCode=函数{return s.split(“”).reduce(函数(a,b){a=((a<<5)-a)+b.charCodeAt(0);返回a&a;}, 0);}//测试console.log(hashCode(“hello”));console.log(hashCode(“这是一个文本。”));console.log(hashCode(“Luis Fonsi的Despacito”));

单线箭头功能版本:

hashCode=s=>s.split(“”).reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);返回a&a},0)//测试console.log(hashCode(“hello”));console.log(hashCode(“这是一个文本。”));console.log(hashCode(“Luis Fonsi的Despacito”));

UUID v3和UUID v5实际上是给定输入字符串的散列。

UUID v3基于MD5,UUID v5基于SHA-1。

因此,最明显的选择是使用UUIDv5。

幸运的是,有一个流行的npm包,其中包括所有UUID算法。

npm install uuid

要实际生成UUIDv5,您需要一个唯一的命名空间。这个名称空间就像种子,应该是常量,以确保给定输入的输出始终相同。具有讽刺意味的是,您应该生成UUID v4作为命名空间。最简单的方法是使用一些在线工具。

一旦你有了一个名称空间,你就一切就绪了。

import { v5 as uuidv5 } from 'uuid';

const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
const hash = uuidv5('input', MY_NAMESPACE);

例如,如果输入字符串始终是URL,则可以使用一些默认名称空间。

const hashForURL = uuidv5('https://www.w3.org/', uuidv5.URL);

String.prototype.hashCode=函数(){var散列=0,i、 chr;如果(this.length==0)返回哈希;对于(i=0;i<this.length;i++){chr=this.charCodeAt(i);哈希=((哈希<<5)-哈希)+chr;哈希|=0;//转换为32位整数}返回哈希;}const str='收入'console.log(str,str.hashCode())

来源