Base62Cipher.java
1.71 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.diligrp.cashier.shared.security;
public final class Base62Cipher {
private static final char[] BASE62_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static final int BASE = 62;
public static String encodeLong(long data) {
if (data < 0) {
throw new IllegalArgumentException("cannot be negative");
}
if (data == 0) {
return String.valueOf(BASE62_CHARS[0]);
}
StringBuilder sb = new StringBuilder();
while (data > 0) {
int remainder = (int) (data % BASE);
sb.append(BASE62_CHARS[remainder]);
data = data / BASE;
}
// 反转字符串(因为取余是从低位到高位,需要反转恢复顺序)
return sb.reverse().toString();
}
public static long decodeLong(String payload) {
if (payload == null || payload.isEmpty()) {
throw new IllegalArgumentException("Invalid base62 data");
}
long result = 0;
for (char c : payload.toCharArray()) {
if (result > (Long.MAX_VALUE - getCharIndex(c)) / BASE) {
throw new NumberFormatException("Invalid base62 data: overflow long");
}
result = result * BASE + getCharIndex(c);
}
return result;
}
private static int getCharIndex(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'z') {
return 10 + (c - 'a');
} else if (c >= 'A' && c <= 'Z') {
return 36 + (c - 'A');
} else {
throw new IllegalArgumentException("invalid base62 data:" + c);
}
}
}