aes加密算法java完整代码
时间: 2024-06-18 21:01:07 浏览: 161
AES(Advanced Encryption Standard)是一种高级加密标准,用于数据的块级加密。在Java中,我们可以使用`javax.crypto.Cipher`类来实现AES加密。以下是一个简单的Java代码示例,展示了如何使用AES进行加密和解密:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
public class AESExample {
private static final String ALGORITHM = "AES";
private static final String KEY = "your_secret_key"; // 用实际的密钥替换此字符串
// 加密方法
public static String encrypt(String data) throws Exception {
Key key = generateAESKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
// 解密方法
public static String decrypt(String encryptedData) throws Exception {
Key key = generateAESKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedData);
}
// 生成AES密钥
private static Key generateAESKey() throws Exception {
return new SecretKeySpec(KEY.getBytes(), ALGORITHM);
}
public static void main(String[] args) {
try {
String originalText = "Hello, World!";
String encrypted = encrypt(originalText);
String decrypted = decrypt(encrypted);
System.out.println("Original: " + originalText);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,这只是一个基本示例,实际应用中你需要妥善管理密钥的安全存储和传递,以及处理可能出现的各种异常。
阅读全文