简单的方案是使用uuid生成, 但太长且数据库检索效率低。
本次使用hashIds的方案 简单 安全。
简述
简单的方案是使用uuid生成, 但太长且数据库检索效率低。
本次使用hashIds的方案 简单 安全。
激活码也算一种发号器, 但直接用序号没有安全可言。
代码
maven坐标
1
2
3
4
5
|
<dependency>
<groupId>org.hashids</groupId>
<artifactId>hashids</artifactId>
<version>1.0.3</version>
</dependency>
|
代码
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
|
import org.hashids.Hashids;
public class GenerateIdDemo {
public static void main(String[] args) { //
// 这里的盐应当无规律,提高安全性
String salt = "this is my salt";
int minHashLength = 5 ; // 加密后的字符串长度最少为5
// 通过自定义哈希字母 剔除易混字符1il、0o
String alphabet = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
Hashids hashids = new Hashids(salt, minHashLength, alphabet);
int standard = 1; // 表明激活码是标准版还是加强版
int pro = 2;
int cloud = 3;
// 用来生成激活码
// 激活码 有状态(是否过期、是否使用过、绑定的机器码) 应当存到数据库中
System.out.println("---- 生成激活码");
System.out.println(hashids.encode(standard, 1));
System.out.println(hashids.encode(standard, 2));
System.out.println(hashids.encode(standard, 3));
System.out.println(hashids.encode(pro, 1));
System.out.println(hashids.encode(pro, 2));
System.out.println(hashids.encode(pro, 3));
String proCode03 = hashids.encode(cloud, 1);
// 激活时 先解析 再去数据库核对是否被使用
long[] decode = hashids.decode(proCode03);
System.out.println("使用激活码--授权版本-"+decode[0] + " 序号-" + decode[1]);
// 加密文章序号
// 通常文章的访问链接类似 www.xxxblog.com/s/1.html 加密后可以变成 wvG5b.html
System.out.println("---- 对文章id加密");
System.out.println(hashids.encode(11));
System.out.println(hashids.encode(12));
// 加密时也可以带上作者的id
int authorId = 61;
System.out.println(hashids.encode(authorId, 11));
System.out.println(hashids.encode(authorId, 12));
}
}
|
文章作者
duansheli
上次更新
2019-12-25
(325c7b3)