JAVA实现AES加解密代码简化版
时间: 2023-10-26 17:54:49 浏览: 127
以下是JAVA实现AES加解密的简化版代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] cipherText = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(cipherText);
}
public static String decrypt(String cipherText, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(plainText);
}
}
```
其中,`encrypt`方法用于加密明文,`decrypt`方法用于解密密文。`key`参数为密钥,需要保证长度为16、24或32个字节。`plainText`和`cipherText`参数分别为明文和密文,均为字符串类型。在进行加密和解密时,需要用到`SecretKeySpec`和`Cipher`这两个类,按照指定的算法和填充方式进行操作即可。
阅读全文