package org.sxkj.common.utils;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.IvParameterSpec;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.nio.charset.StandardCharsets;
|
import java.util.Base64;
|
|
/**
|
* AES 密码加密
|
*/
|
public class AESUtil {
|
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
|
private static final String SECRET_KEY = "a12345678901234r5678901234567890"; // 256-bit key
|
private static final String IV = "9185367198901234"; // 16-byte IV
|
|
public static String encrypt(String data){
|
try {
|
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
|
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
|
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
|
return Base64.getEncoder().encodeToString(encrypted);
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new RuntimeException(e);
|
}
|
}
|
|
public static String decrypt(String encryptedData){
|
try {
|
SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
|
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
|
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
|
return new String(original, StandardCharsets.UTF_8);
|
} catch (Exception e) {
|
e.printStackTrace();
|
throw new RuntimeException(e);
|
}
|
}
|
|
}
|