aes加密 java
时间: 2023-11-18 22:54:16 浏览: 37
好的,关于 AES 加密,Java 提供了 javax.crypto 包来实现。具体步骤如下:
1. 创建一个 KeyGenerator 对象,指定加密算法为 AES。
2. 通过 KeyGenerator 生成一个 SecretKey 对象,该对象包含了加密所需的密钥。
3. 创建一个 Cipher 对象,指定加密模式和填充方式。
4. 通过 Cipher 对象的 init() 方法,指定加密模式和密钥。
5. 调用 Cipher 对象的 doFinal() 方法,对需要加密的数据进行加密。
下面是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AesUtil {
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 128;
public static String encrypt(String data, String key) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(key);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String data, String key) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(key);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(data));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static String generateKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(KEY_SIZE);
SecretKey secretKey = keyGenerator.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
}
```
其中,encrypt() 方法用于加密数据,decrypt() 方法用于解密数据,generateKey() 方法用于生成密钥。