package com.hxzk.gps.util.AES; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Base64; public class AES { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; private static final String PUBLIC_KEY = "KTbVslm2mvQLoD3p"; private static final int IV_SIZE = 16; // AES 的 IV 长度为 16 字节 /** * 加密方法 * * @param plainText 明文 * @return 加密后的 Base64 编码字符串,包含 IV 和密文 * @throws Exception 异常 */ public static String encrypt(String plainText) throws Exception { // 生成随机的 IV byte[] ivBytes = new byte[IV_SIZE]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(ivBytes); IvParameterSpec iv = new IvParameterSpec(ivBytes); byte[] keyBytes = PUBLIC_KEY.getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); // 将 IV 和密文拼接在一起 byte[] combined = new byte[IV_SIZE + encryptedBytes.length]; System.arraycopy(ivBytes, 0, combined, 0, IV_SIZE); System.arraycopy(encryptedBytes, 0, combined, IV_SIZE, encryptedBytes.length); return Base64.getEncoder().encodeToString(combined); } /** * 解密方法 * * @param encryptedText 加密后的 Base64 编码字符串,包含 IV 和密文 * @return 解密后的明文 * @throws Exception 异常 */ public static String decrypt(String encryptedText) throws Exception { // 将空格替换成 = 号 String replacedText = encryptedText.replace(" ", "+"); byte[] combined = Base64.getDecoder().decode(replacedText); // 提取 IV byte[] ivBytes = new byte[IV_SIZE]; System.arraycopy(combined, 0, ivBytes, 0, IV_SIZE); IvParameterSpec iv = new IvParameterSpec(ivBytes); // 提取密文 byte[] encryptedBytes = new byte[combined.length - IV_SIZE]; System.arraycopy(combined, IV_SIZE, encryptedBytes, 0, encryptedBytes.length); byte[] keyBytes = PUBLIC_KEY.getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, StandardCharsets.UTF_8); } public static void main(String[] args) { try { // 模拟从请求中获取的参数 String param1 = "szhang"; String param2 = "SZhang13439350593"; // 多次加密相同的参数 String encryptedParam1 = encrypt(param1); String encryptedParam2 = encrypt(param2); System.out.println("加密后的 username: " + encryptedParam1); System.out.println("加密后的 password: " + encryptedParam2); // 解密参数 String decryptedParam1 = decrypt(encryptedParam1); String decryptedParam2 = decrypt(encryptedParam2); System.out.println("解密后的 username: " + decryptedParam1); System.out.println("解密后的 password: " + decryptedParam2); } catch (Exception e) { e.printStackTrace(); } } }