aes加密工具java
时间: 2023-10-17 20:25:55 浏览: 52
在Java中,可以使用javax.crypto包中的AES算法来进行加密。具体来说,可以使用SecretKey类生成一个AES密钥,然后使用Cipher类来进行加密和解密操作。以下是一个使用AES加密的示例代码:
```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;
public class AESUtil {
private static final String AES_ALGORITHM = "AES";
public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES_ALGORITHM);
keyGenerator.init(128);
return keyGenerator.generateKey();
}
public static byte[] encrypt(String plaintext, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
}
public static String decrypt(byte[] ciphertext, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(ciphertext);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
```
使用这个工具类,你可以生成一个AES密钥,然后使用该密钥对数据进行加密和解密操作。示例代码中的`encrypt`方法接受一个明文字符串和一个AES密钥,返回加密后的字节数组。`decrypt`方法接受一个密文字节数组和一个AES密钥,返回解密后的明文字符串。
请注意,为了运行这段代码,你需要导入Java的加密包(javax.crypto)和字符集包(java.nio.charset)。
希望这个示例能够帮助你理解如何使用Java中的AES加密工具。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Java轻松的AES加密解密工具](https://blog.csdn.net/Janson_Lin/article/details/107013898)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]