package com.core.common;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.nio.charset.StandardCharsets;
|
|
public class AesUtils {
|
|
private static final String DEFAULT_CHARSET = "utf-8";
|
private static final int DEFAULT_KEY_LENGTH = 16;
|
|
public static String encrypt(String data, String key) {
|
try {
|
if (key == null || "".equals(key) || key.length() != DEFAULT_KEY_LENGTH) {
|
return null;
|
}
|
byte[] raw = key.getBytes(StandardCharsets.UTF_8);
|
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
|
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
|
return RadixTools.bytesToHexStr(encrypted);
|
} catch (Exception ex) {
|
return null;
|
}
|
}
|
|
public static String decrypt(String data, String key) {
|
try {
|
if (key == null || "".equals(key) || key.length() != DEFAULT_KEY_LENGTH) {
|
return null;
|
}
|
byte[] raw = key.getBytes(StandardCharsets.UTF_8);
|
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
|
byte[] original = cipher.doFinal(RadixTools.hexStringToBytes(data));
|
return new String(original, StandardCharsets.UTF_8);
|
} catch (Exception ex) {
|
return null;
|
}
|
}
|
|
public static void main(String[] args) {
|
String key = "123456";
|
String data = "15988786205×tamp=" + (System.currentTimeMillis() + 5000000L);
|
System.out.println(System.currentTimeMillis() + 5000000L);
|
System.out.println(encrypt(data, key));
|
}
|
}
|