用java 写一篇aes算法
时间: 2023-11-18 19:59:59 浏览: 36
好的,这里是一个使用Java实现AES算法的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
private static final String KEY = "mySecretKey12345"; // 密钥,16个字符
public static void main(String[] args) throws Exception {
String originalText = "Hello World!"; // 原始文本
// 加密
byte[] encryptedBytes = encrypt(originalText.getBytes(StandardCharsets.UTF_8));
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("加密后:" + encryptedText);
// 解密
byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
System.out.println("解密后:" + decryptedText);
}
private static byte[] encrypt(byte[] input) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(input);
}
private static byte[] decrypt(byte[] input) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return cipher.doFinal(input);
}
}
```
该示例代码使用AES算法对原始文本进行加密和解密,其中使用了ECB模式和PKCS5Padding填充方式。在加密过程中,首先将密钥转换为SecretKeySpec对象,然后使用Cipher类进行加密或解密操作。加密后的结果使用Base64进行编码以便于传输和存储。在解密过程中,将Base64编码的密文进行解码,然后使用同样的密钥和算法进行解密操作即可得到原始文本。