package com.dechnic.tfoms.util;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* @ desc:
* @ Author: houqida
* @ Date : 2023/6/28
*/
public class EncryptUtil {
private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class);
public static String decryptAes(String sSrc,String sKey){
try {
if (sKey == null) {
logger.info("Key为空null");
return "";
}
if (sKey.length() != 16) {
logger.info("Key长度不是16位");
return "";
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
logger.error("密码解密出错",e);
return null;
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static String encryptAes(String sSrc,String sKey){
if (sKey == null) {
logger.info("Key为空null");
return "";
}
if (sKey.length() != 16) {
logger.info("Key长度不是16位");
return "";
}
try {
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw,"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[] bytes = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
return new BASE64Encoder().encode(bytes);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
}