java实现AES加解密
时间: 2023-11-18 14:04:27 浏览: 37
Java可以使用javax.crypto包中的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[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) {
try {
String plainText = "Hello, World!";
String key = "ThisIsASecretKey"; // 密钥长度必须是16、24或32字节
String encryptedText = encrypt(plainText, key);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码使用AES/ECB/PKCS5Padding算法进行加解密,密钥长度必须是16、24或32字节。在示例中,明文为"Hello, World!",密钥为"ThisIsASecretKey"。运行代码后,会输出加密后的密文和解密后的明文。请注意,实际使用中应该使用更安全的加密模式和生成更强大的密钥。