JAVA实现AES主要代码
时间: 2023-10-26 14:54:42 浏览: 34
以下是Java实现AES加密和解密的主要代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* AES加密
*
* @param content 需要加密的字符串
* @param key 密钥
* @return 加密后的字符串
*/
public static String encrypt(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* AES解密
*
* @param content 需要解密的字符串
* @param key 密钥
* @return 解密后的字符串
*/
public static String decrypt(String content, String key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(content));
return new String(decrypted, StandardCharsets.UTF_8);
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) throws Exception {
String content = "Hello, world!";
String key = "1234567890abcdef";
// 加密
String encrypted = AESUtil.encrypt(content, key);
System.out.println("加密后的字符串:" + encrypted);
// 解密
String decrypted = AESUtil.decrypt(encrypted, key);
System.out.println("解密后的字符串:" + decrypted);
}
}
```