在进行AES加密时,需要使用安全的加密模式,而不是ECB模式。同时需要填充输入数据以避免NoPadding错误。可采用以下代码进行加密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
public static String encrypt(String keyStr, String plainText) throws Exception {
byte[] keyBytes = keyStr.getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String keyStr, String encryptedText) throws Exception {
byte[] keyBytes = keyStr.getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
其中,AES加密使用的是PKCS5Padding填充方式,可以保证输入数据的长度为16的倍数。同时,使用Base64对加密结果进行编码以便于传输。