目录
1、Hashids的简介
Hashids是一个小型的开源库,它从数字生成简短的、惟一的、非顺序的id。它将像347这样的数字转换成像“yr8”这样的字符串,或者像[27,986]这样的数字数组转换成“3kTMd”。您还可以解码这些id。这对于将多个参数绑定到一个或简单地将它们用作简短的uid非常有用。
官网:https://hashids.org/objective-c/
Maven依赖
<dependency> |
Hashids具有自定义独特的salt,在保证salt不变的情况下进行加密和解密
在以下方法中默认使用盐值为“this is my salt”
2、hashids加密和解密单个id
例:将单个id为1进行加密和解密,默认盐值“this is my salt”
Hashids hashids= new Hashids("this is my salt"); |
输出结果:
3、变更salt加密和解密单个id
例:将单个id为1进行加密和解密,默认盐值“this is my salt”,变更后盐值“this is transfer salt”
Hashids hashids= new Hashids("this is my salt"); //加密数字1 String hashStr = hashids.encode(1); System.out.println("1加密后值为:"+hashStr); //salt不变解密数字1 long[] hashNums = hashids.decode(hashStr); for (int i = 0; i < hashNums.length; i++) { System.out.println("salt不变解密后值为:" + hashNums[i]); } //变更salt解密数字1 Hashids hashidsT= new Hashids("this is transfer salt"); long[] hashNumsT = hashidsT.decode(hashStr); for (int i = 0; i < hashNumsT.length; i++) { System.out.println("变更salt解密后值为:" + hashNumsT[i]); } |
输出结果:
可见salt变更后不会进行解密输出,因为long[]为空
4、hashids加密和解密多个id
例:将多个id分别为1,2,3,4,5,6进行加密和解密,默认盐值“this is my salt”
Hashids hashids = new Hashids("this is my salt"); //加密数字1 String hashStr = hashids.encode(1, 2, 3, 4, 5, 6); System.out.println("多个id加密后值为:" + hashStr); //解密数字1 long[] hashNums = hashids.decode(hashStr); for (int i = 0; i < hashNums.length; i++) { System.out.println("多个id解密后,第" + i + "个值为:" + hashNums[i]); } |
输出结果:
5、hashids自定义设置最小哈希长度
例:自定义设置最小哈希长度为6,将id为1进行加密和解密,默认盐值“this is my salt”
Hashids hashids = new Hashids("this is my salt",6); //加密数字1 String hashStr = hashids.encode(1); System.out.println("自定义哈希长度加密1后值为:"+hashStr); //解密数字1 long[] hashNums = hashids.decode(hashStr); for (int i = 0; i < hashNums.length; i++) { System.out.println("自定义哈希长度解密1后值为:" + hashNums[i]); } |
输出结果:
6、hashids自定义设置哈希字母表
自定义哈希字母表时,需要注意在自定义的哈希字母表中0-9个这十个数字每个都必须出现,每个数字可重复多次,英文字母至少要出现6个字母,不分大小写
例:自定义哈希字母表为“0123456789aJDYGC”,将id为1进行加密和解密,默认盐值“this is my salt”
Hashids hashids = new Hashids("this is my salt", 0, "0123456789aJDYGC"); String hashStr = hashids.encode(1); System.out.println("自定义哈希字母表加密1后值为:" + hashStr); long[] hashNums= hashids.decode(hashStr); for (int i = 0; i < hashNums.length; i++) { System.out.println("自定义哈希字母表解密1后值为:" + hashNums[i]); } |
输出结果: