我需要将字符串转换为某种形式的哈希。这在JavaScript中是可能的吗?
我没有使用服务器端语言,所以我不能这样做。
我需要将字符串转换为某种形式的哈希。这在JavaScript中是可能的吗?
我没有使用服务器端语言,所以我不能这样做。
当前回答
我参加派对有点晚了,但你可以使用这个模块:加密:
const crypto = require('crypto');
const SALT = '$ome$alt';
function generateHash(pass) {
return crypto.createHmac('sha256', SALT)
.update(pass)
.digest('hex');
}
此函数的结果始终是64个字符的字符串;类似于:“aa54e7563b1964037849528e7ba068eb7767b1fab74a8d80fe300828b996714a”
其他回答
添加这一点是因为还没有人这样做,而这似乎是用哈希来要求和实现的,但它总是做得很糟糕。。。
这需要一个字符串输入和您希望哈希值相等的最大值,并根据字符串输入生成一个唯一的数字。
您可以使用它来生成图像数组中的唯一索引(如果您希望为用户返回一个特定的化身,该化身是随机选择的,但也是基于其名称选择的,因此它将始终分配给具有该名称的人)。
当然,您也可以使用它将索引返回到颜色数组中,例如根据某人的姓名生成独特的化身背景颜色。
function hashInt (str, max = 1000) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash = hash & hash;
}
return Math.round(max * Math.abs(hash) / 2147483648);
}
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”));
这是一个快速而简洁的版本,改编自这里:
String.prototype.hashCode = function() {
var hash = 5381, i = this.length
while(i)
hash = (hash * 33) ^ this.charCodeAt(--i)
return hash >>> 0;
}
这是一个改进的、性能更好的变体,与Java对CharSequence的标准object.hashCode()的实现相匹配。
String.prototype.hashCode = function() {
var hash = 0, i = 0, len = this.length;
while ( i < len ) {
hash = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
}
return hash;
};
这里还有一个只返回正散列码的函数:
String.prototype.hashcode = function() {
return this.hashCode()+ 2147483647 + 1;
};
这里有一个匹配的Java,它只返回正散列码:
public static long hashcode(Object obj) {
return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
}
对于那些不想将其附加到字符串的人,没有原型:
function hashCode(str) {
var hash = 0, i = 0, len = str.length;
while ( i < len ) {
hash = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
}
return hash;
}
function hashcode(str) {
hashCode(str) + 2147483647 + 1;
}
享受
@esmiralha答案的略微简化版本。
我不会在这个版本中重写String,因为这可能会导致一些不希望的行为。
function hashCode(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
}
return hash;
}