游戏中要去校验用户名是否重复,redis中放中文的key貌似蛮怪的吧,还是hash后放数字吧,从而校验是否冲突;
hash冲突 例如“Af”和“BG”哈希值相同,则有“AfAf”,“AfBG”,“BGAf”,“BGBG”的哈希值也相同
具体关于java的Hash冲突攻击 可以参考此文章:http://keary.cn/?p=845
不废话了,实际双hash用途很多,还有就是java中的自带hash会出现负数比如 (-8%3) 就为-2 依赖取模后的值就会出问题;
上代码:
package com.leeyz.idea.test;
public class TestHash {
public static void main(String[] args) {
String str = "中文";
System.out.println(str.hashCode());
System.out.println("s".hashCode());
System.out.println("S".hashCode());
System.out.println("cat".hashCode());
System.out.println("Af".hashCode());
System.out.println("BG".hashCode());
System.out.println(FNVHash1Uint("Af"));
System.out.println(FNVHash1Uint("BG"));
System.out.println(mixHashULong("Af"));
System.out.println(mixHashULong("BG"));
System.out.println(-8%3);
}
public static long mixHashULong(String str) {
long hash = (str.hashCode() & 0x7fffffff) * 1L;
hash <<= 32;
hash |= FNVHash1Uint(str);
return hash;
}
public static int FNVHash1Uint(String str) {
byte[] data = str.getBytes();
final int p = 16777619;
int hash = (int) 2166136261L;
for (byte b : data)
hash = (hash ^ b) * p;
hash += hash << 13;
hash ^= hash >> 7;
hash += hash << 3;
hash ^= hash >> 17;
hash += hash << 5;
return (hash & 0x7fffffff);
}
}