import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.security.PublicKey;
import java.util.List;
@Slf4j
public class MakeSure {
static final String tokenPath = "/usr/data/token.db";
static final String pubKeyPath = "/usr/data/rsa.pub";
private static PublicKey publicKey;
public static boolean init() {
log.info("pubKeyPath->{}", pubKeyPath);
try {
//首先判断公钥是否存在,不存在则先生成公钥私钥
File pubKey = new File(pubKeyPath);
if (!pubKey.exists()) {
return false;
}
//公钥私钥都存在
publicKey = RsaUtils.getPublicKey(pubKeyPath);
List<String> macs = MacTools.getMacList();
String macAddress = getMacAddress(publicKey, getTokenString());
log.info("macAddress->{}", macAddress);
log.info("本机的mac网卡的地址有:"+macs);
if (StringUtils.isBlank(macAddress)) {
return false;
}
for (String mac : macs) {
if (mac.equals(macAddress)) {
return true;
}
}
return false;
} catch (Exception e) {
log.error("初始化公钥失败",e);
throw new RuntimeException();
}
}
public static String getTokenString() {
String tokenString;
byte[] strBuffer = null;
int flen = 0;
File xmlfile = new File(tokenPath);
try {
InputStream in = new FileInputStream(xmlfile);
flen = (int)xmlfile.length();
strBuffer = new byte[flen];
in.read(strBuffer, 0, flen);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
tokenString = new String(strBuffer);
return tokenString;
}
public static String getMacAddress(PublicKey publicKey, String token) {
try{
Jws<Claims> claimsJws = parseJwt(publicKey, token);
Claims body = claimsJws.getBody();
return body.get("macAddress", String.class);
} catch(Exception e){
log.error(TraceUtil.getTrace(e));
throw new RuntimeException();
}
}
public static Jws<Claims> parseJwt(PublicKey publicKey, String token) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
public static void main(String[] args) {
init();
}
}