双hash减少用户名冲突JAVA版
星期五, 2015-05-08 | Author: Lee | JAVA-and-J2EE, 游戏开发 | 3,812 views
游戏中要去校验用户名是否重复,redis中放中文的key貌似蛮怪的吧,还是hash后放数字吧,从而校验是否冲突;
hash冲突 例如“Af”和“BG”哈希值相同,则有“AfAf”,“AfBG”,“BGAf”,“BGBG”的哈希值也相同
具体关于java的Hash冲突攻击 可以参考此文章:http://keary.cn/?p=845
不废话了,实际双hash用途很多,还有就是java中的自带hash会出现负数比如 (-8%3) 就为-2 依赖取模后的值就会出问题;
上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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); } } |
文章作者: Lee
本文地址: https://www.pomelolee.com/1462.html
除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址
No comments yet.
Leave a comment
Search
相关文章
热门文章
最新文章
文章分类
- ajax (10)
- algorithm-learn (3)
- Android (6)
- as (3)
- computer (85)
- Database (30)
- disucz (4)
- enterprise (1)
- erlang (2)
- flash (5)
- golang (3)
- html5 (18)
- ios (4)
- JAVA-and-J2EE (186)
- linux (143)
- mac (10)
- movie-music (11)
- pagemaker (36)
- php (50)
- spring-boot (2)
- Synology群晖 (2)
- Uncategorized (6)
- unity (1)
- webgame (15)
- wordpress (33)
- work-other (2)
- 低代码 (1)
- 体味生活 (40)
- 前端 (21)
- 大数据 (8)
- 游戏开发 (9)
- 爱上海 (19)
- 读书 (4)
- 软件 (3)