java通过aes对消息加密解密的代码
时间: 2024-04-03 09:33:32 浏览: 5
以下是Java中使用AES对消息进行加密解密的代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesEncryption {
private static final String ALGORITHM = "AES";
private static final String KEY = "mySecretKey12345"; // 密钥,必须是16位
// 加密
public static String encrypt(String plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密
public static String decrypt(String encryptedText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
}
```
使用方法:
```java
String plainText = "Hello World";
String encryptedText = AesEncryption.encrypt(plainText);
String decryptedText = AesEncryption.decrypt(encryptedText);
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
```
注意,以上代码中的KEY是密钥,必须是16位。在实际应用中,需要保护好密钥,避免密钥泄露导致数据的安全性问题。