import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class AESUtils {
/**
* 16 进制字符
*/
private static final char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static void main(String[] args) throws Exception {
String AES_KEY = "Pt120ΦV1ΘcΣLσEοjbΓMιfΦeΧyAUK5Ψ5ΙBνJΚS6γλB34m58ΞςEθ";
for (int i = 0; i < 10; i++) {
Thread.sleep(200);
long start = System.currentTimeMillis();
String e = encrypt("{\"timestamp\":\"" + System.currentTimeMillis() + "\"}", AES_KEY);
System.out.println(e);
String s = decrypt(e, AES_KEY);
System.out.println(s);
System.out.println(System.currentTimeMillis() - start);
}
}
public static String encrypt(String text, String key) {
try {
// 创建AES的 key 生成器
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128, new SecureRandom(key.getBytes()));
// 生成密钥
SecretKey secretKey = generator.generateKey();
byte[] encoded = secretKey.getEncoded();
// 生成AES专用密钥Key
SecretKeySpec spec = new SecretKeySpec(encoded, "AES");
Cipher cipher = Cipher.getInstance("AES");
byte[] content = text.getBytes(StandardCharsets.UTF_8);
cipher.init(Cipher.ENCRYPT_MODE, spec); // 加密模式
return byteToHex(cipher.doFinal(content));
} catch (Exception ignore) {
}
return null;
}
public static String byteToHex(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
int hex = b & 0xFF;
builder.append(digit[hex / 16])
.append(digit[hex % 16]);
}
return builder.toString();
}
/**
* 字符转换为 16进制整型
*
* @param c 0~9 A~F
* @return hex
*/
private static int hexToInt(char c) {
if (c <= '9') {
return c - 48;
} else {
return c - 55; // A = 10 ,so c>=65 { c - 55}
}
}
public static String decrypt(String content, String key) {
// content = content.toUpperCase();
try {
byte[] bArrays = new byte[content.length() / 2];
int j = 0;
for (int i = 0; i < content.length(); i += 2) {
int b = hexToInt(content.charAt(i)) * 16 + hexToInt(content.charAt(i + 1));
bArrays[j++] = (byte) b;
}
// 创建AES的 key 生成器
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128, new SecureRandom(key.getBytes()));
SecretKey secretKey = generator.generateKey();
byte[] encoded = secretKey.getEncoded();
// 转换为AES专用密钥
SecretKeySpec spec = new SecretKeySpec(encoded, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, spec);
return new String(cipher.doFinal(bArrays), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Anyway, there are so many encryption and decryption, you should not see my frustration, right?