以下方法输入格式:HEX,输出格式:HEX(注释的代码输入格式:UTF8,输出格式:UTF8);密钥使用的是固定的string格式,并且密钥长度要满足16
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
public static String encryptToHex(String data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 使用PKCS5Padding,等同于PKCS#7Padding
cipher.init(Cipher.ENCRYPT_MODE, key);
// byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] encryptedBytes = cipher.doFinal(hexStringToByteArray(data));
// 将加密后的字节转换为十六进制字符串
StringBuilder hexString = new StringBuilder(2 * encryptedBytes.length);
for (byte b : encryptedBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString().toUpperCase();
}
public static String decryptFromHex(String hex, SecretKey key) throws Exception {
// 将十六进制字符串转换回字节
byte[] data = new byte[hex.length() / 2];
for (int i = 0; i < data.length; i++) {
int index = i * 2;
int value = Integer.parseInt(hex.substring(index, index + 2), 16);
data[i] = (byte) value;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(data);
// return new String(decryptedBytes, StandardCharsets.UTF_8);
return ByteUtils.byteArrayToHexString(decryptedBytes);
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
String keyString = "xxxxx";
byte[] keyBytes = keyString.substring(0, 16).getBytes(StandardCharsets.UTF_8);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
}