This repository has been archived on 2025-03-01. You can view files and clone it, but cannot push or open issues or pull requests.
Bonus-Cloud-Smart-Canteen/bonus-common-biz/src/main/java/com/bonus/utils/AesEncryptUtil.java

72 lines
2.4 KiB
Java

package com.bonus.utils;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
//import net.xnzn.core.common.config.sys.EncryptProperties;
//import net.xnzn.core.common.encrypt.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
@Component
public class AesEncryptUtil {
private static final Logger log = LoggerFactory.getLogger(AesEncryptUtil.class);
private static final String KEY_ALGORITHM = "AES";
private static final String AES_ENCRYPT_KEY = "pigxpigxpigxpigx";
// @Resource
// private EncryptProperties encryptProperties;
//
// public static AesEncryptUtil getInstance() {
// return (AesEncryptUtil) SpringContextHolder.getBean(AesEncryptUtil.class);
// }
public static String aesEncrypt(String encryptStr) {
if (StrUtil.isBlank(encryptStr)) {
return encryptStr;
} else {
AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(AES_ENCRYPT_KEY.getBytes(), "AES"), new IvParameterSpec(AES_ENCRYPT_KEY.getBytes()));
return aes.encryptBase64(encryptStr);
}
}
public static String aesDecode(String decodeStr) {
if (StrUtil.isBlank(decodeStr)) {
return decodeStr;
} else {
AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(AES_ENCRYPT_KEY.getBytes(), "AES"), new IvParameterSpec(AES_ENCRYPT_KEY.getBytes()));
byte[] resultByte;
try {
resultByte = aes.decrypt(Base64.decode(decodeStr.getBytes(StandardCharsets.UTF_8)));
} catch (Exception var5) {
log.info("字段解密异常:" + var5.getMessage());
return decodeStr;
}
return (new String(resultByte, StandardCharsets.UTF_8)).trim();
}
}
public static void main(String[] args) {
System.out.println(aesEncrypt("Bonus$2026"));
System.out.println(aesDecode("PCAGz8j5ByU2AzoT6vtlLA=="));
System.out.println();
System.out.println(aesEncrypt("Bonus$2027"));
System.out.println(aesDecode("MF1Nui79h/OHRGoUx1jhcg=="));
System.out.println();
System.out.println(aesEncrypt("Bd@19901"));
System.out.println(aesDecode("mgURks4Khhn55E1qSpw8ZA=="));
}
}