package com.usercenter.common.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
/**
* 加解密工具类
*/
public class AESUtils {
private static final String SECRET_KEY = "FzRLnDiS7Ry0K9Ew";
public static String encrypt(String plainText) {
if (plainText == null || plainText.isEmpty()) {
return "";
}
try {
byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
//解决javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
byte[] bytes = Arrays.copyOf(plainBytes, 16);
byte[] cipherBytes = cipher.doFinal(bytes);
return Base64.getEncoder().encodeToString(cipherBytes);
} catch (Exception e) {
return "";
}
}
public static String decrypt(String ciphertext) {
if (ciphertext == null || ciphertext.isEmpty()) {
return "";
}
try {
byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
byte[] cipherBytes = Base64.getDecoder().decode(ciphertext);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] plainBytes = cipher.doFinal(cipherBytes);
// 移除末尾的0字符
int lastNonNullIndex = plainBytes.length - 1;
while (lastNonNullIndex >= 0 && plainBytes[lastNonNullIndex] == 0) {
lastNonNullIndex--;
}
return new String(plainBytes, 0, lastNonNullIndex + 1, StandardCharsets.UTF_8);
} catch (Exception e) {
return "";
}
}
}
AES加解密及解决javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
于 2024-01-31 09:41:46 首次发布