package com.sensor.sellCabinet.util;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
/**
* @author 辛毅
* @date 2020/11/20
*/
@Slf4j
@Component
@ConditionalOnClass(RSA.class)
public class CryptHelper {
private static String privateKey="";
private static String publicKey="";
private final RSA rsa;
public CryptHelper() {
this.rsa = new RSA(privateKey, publicKey);
}
public String encrypt(String originString) {
return rsa.encryptBase64(originString, KeyType.PublicKey);
}
public String decrypt(String encryptString) {
return new String(rsa.decryptFromBase64(encryptString,KeyType.PrivateKey));
}
/* public static void main(String[] args) throws Exception{
String a="111111\n" +
"1625549789963";
System.out.println(new CryptHelper().encrypt(a));
String s = "c1yB8wyDFeYd9pvk0CJagy5BhxKMjbTd3nQv7NjwMof2PNELhuzELWtiNt3VcGWhAUrARVd2T4ecSsbd5ywF4YhCFfJjyQ07fC4z6kAQ6GQ2Pu/2WP4Gfn+XeyLtG3FMtmC6gNnUPUqeZGCxlsgHuF4oGUkcPZHrStbJ+1/XV+U=";
System.out.println(new CryptHelper().decrypt(s));
}*/
/**
* 解密并校验时间戳
*
* @param encryptString 原文 + '\n' + 时间戳,加密后的字符串
* @return 原文
*/
public String decryptWithTimestamp(String encryptString) {
String str = rsa.decryptStr(encryptString, KeyType.PrivateKey);
String[] split = str.split("\n");
if (split.length == 2) {
long timestamp = Long.parseLong(split[1]);
long now = System.currentTimeMillis();
// 时间差超过三个小时,判定为伪造数据
if (Math.abs(now - timestamp) > 3 * 3600 * 1000) {
log.error("解密字符串中时间戳距离当前时间超过三个小时,解密结果无效 {}", str);
throw new RuntimeException("解密失败");
}
}
return split[0];
}
/**
* 加密
*
* @param password 原文 + '\n' + 时间戳,加密后的字符串
* @return 原文
*/
public String decryptPassword(String password) {
long now = System.currentTimeMillis();
String encryptString = password+"\n"+now;
return encrypt(encryptString);
}
}