public class AesUtils {
private static final String AES_MODE = "AES/ECB/NoPadding";
private static final int BLOCK_SIZE = 16;
private byte[] key=null;
private static byte[] generateKey() {
//结尾0等同于C++字符串结尾的\0
String strKey=“1234567890123450”;
byte[] keyBytes = new byte[16];
keyBytes = strKey.getBytes(StandardCharsets.UTF-8);
return keyBytes;
}
// ZeroPadding
private static byte[] zeroPad(byte[] data) {
if (data.length % BLOCK_SIZE == 0) {
return data;
}
int paddedLength = ((data.length + BLOCK_SIZE - 1) / BLOCK_SIZE) * BLOCK_SIZE;
return Arrays.copyOf(data, paddedLength);
}
private static String delZero(byte[] decrypted) {
int length = decrypted.length;
while (length > 0 && decrypted[length - 1] == 0) {
length--;
}
return new String(decrypted, 0, length, StandardCharsets.UTF_8);
}
public static String encrypt(String plainText) {
try {
byte[] key = generateKey();
byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
byte[] padded = zeroPad(plainBytes);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(AES_MODE);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(padded);
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
throw new RuntimeException("AES加密失败", e);
}
}
public static String decrypt(String base64Cipher) {
try {
byte[] key = processKey("");
byte[] encrypted = Base64.getDecoder().decode(base64Cipher);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(AES_MODE);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return delZero(decrypted);
} catch (Exception e) {
throw new RuntimeException("AES解密失败", e);
}
}
}
1万+

被折叠的 条评论
为什么被折叠?



