import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Base64;
public class TokenUtil {
public static String encode(String password, int[] mapper){
String timestamp = String.valueOf(System.currentTimeMillis());
int tLen = timestamp.length();
timestamp = tLen>13 ? timestamp.substring(tLen-13) : timestamp;
timestamp = Base64.getEncoder().encodeToString(timestamp.getBytes());
tLen = timestamp.length();
password = Base64.getEncoder().encodeToString(password.getBytes());
int pLen = password.length();
int j = 0, k = 0;
char[] result = new char[tLen + pLen];
for(int i=0; i<result.length; i++){
if((i%2==0 && j<tLen) || k>=pLen){
result[i] = timestamp.charAt(mapper[j]);
j++;
}else{
result[i] = password.charAt(k);
k++;
}
}
return String.valueOf(result);
}
public static Token decode(String token, int[] mapper){
int j = 0, k = 0;
int len = token.length(), tLen = mapper.length, pLen = len-tLen;
char[] timestamp = new char[tLen], password = new char[pLen];
for(int i=0; i<len; i++){
if((i%2==0 && j<tLen) || k>=pLen){
timestamp[mapper[j]] = token.charAt(i);
j++;
}else{
password[k] = token.charAt(i);
k++;
}
}
String time = String.valueOf(timestamp);
String pwd = String.valueOf(password);
time = new String(Base64.getDecoder().decode(time));
pwd = new String(Base64.getDecoder().decode(pwd));
return new Token(Long.valueOf(time), pwd);
}
@Data
@AllArgsConstructor
static class Token{
private long timestamp;
private String password;
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.util.*;
public class Test{
private static long lastTimestamp = 0;
public static void main(String[] args) {
String password = "abcd12345";
int[] mapper = {15, 6, 17, 4, 10, 11, 13, 8, 19, 2, 0, 14, 12, 3, 9, 18, 16, 1, 5, 7};
String tokenVal = TokenUtil.encode(password, mapper);
System.out.println(tokenVal);
TokenUtil.Token token = TokenUtil.decode(tokenVal, mapper);
long timestamp = token.getTimestamp();
String pwd = token.getPassword();
System.out.println(timestamp);
System.out.println(pwd);
if(timestamp>lastTimestamp && password.equals(pwd)){
lastTimestamp = timestamp;
System.out.println("认证通过...");
}else{
System.out.println("认证失败...");
}
}
}
4YkWAJMjUZ2DTENy=MYzMQU1Mwj=NTz1
1603956561584
abcd12345
认证通过...