目录
1、Hashids 的简介
Hashids 是一个小型的开源库,它从数字生成简短的、惟一的、非顺序的 id。它将像 347 这样的数字转换成像 “yr8” 这样的字符串,或者像[27,986]这样的数字数组转换成 “3kTMd”。您还可以解码这些 id。这对于将多个参数绑定到一个或简单地将它们用作简短的 uid 非常有用。
官网:https://hashids.org/objective-c/
Maven 依赖
Hashids 具有自定义独特的 salt, 在保证 salt 不变的情况下进行加密和解密
在以下方法中默认使用盐值为 “this is my salt”
2、hashids 加密和解密单个 id
例:将单个 id 为 1 进行加密和解密,默认盐值 “this is my salt”
Hashids hashids= new Hashids(“this is my salt”);
// 加密数字 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(“解密后值为:” + hashNums[i]);
}
输出结果:
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]); }
输出结果: