Java 中使用 AES 加密与解密272
高级加密标准 (AES) 是一种对称块密码算法,广泛用于需要高安全性的加密和解密。在本文中,我们将探讨如何使用 Java 中的 包来实现 AES 加密和解密。
创建 AES 密钥
AES 密钥可以是 128、192 或 256 位。要创建 AES 密钥,可以使用以下代码:```java
import ;
import ;
import ;
import ;
public class AESKeyGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException {
// 指定算法为 AES
String algorithm = "AES";
// 创建密钥生成器
KeyGenerator keyGenerator = (algorithm);
// 初始化密钥生成器
(128);
// 生成密钥
SecretKey key = ();
// 输出生成的密钥
("AES密钥:" + key);
}
}
```
AES 加密
要对数据进行 AES 加密,可以使用以下代码:```java
import ;
import ;
import ;
import ;
import ;
import ;
public class AESEncrypt {
public static void main(String[] args) throws Exception {
// 指定算法和工作模式
String algorithm = "AES/CBC/PKCS5Padding";
// 生成密钥
KeyGenerator keyGenerator = ("AES");
SecretKey key = ();
// 创建初始化向量(IV)
// IV 是一个随机值,结合密钥用于加密和解密
byte[] iv = new byte[16];
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
// 创建加密器
Cipher cipher = (algorithm);
(Cipher.ENCRYPT_MODE, key, paramSpec);
// 加密数据
String plaintext = "这是要加密的明文";
byte[] ciphertext = ((StandardCharsets.UTF_8));
// 输出加密后的密文
("密文:" + new String(ciphertext, StandardCharsets.UTF_8));
}
}
```
AES 解密
要对经过 AES 加密的数据进行解密,可以使用以下代码:```java
import ;
import ;
import ;
import ;
import ;
import ;
public class AESDecrypt {
public static void main(String[] args) throws Exception {
// 指定算法、工作模式和填充方式
String algorithm = "AES/CBC/PKCS5Padding";
// 生成密钥
KeyGenerator keyGenerator = ("AES");
SecretKey key = ();
// 创建初始化向量(IV)
byte[] iv = new byte[16];
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
// 创建解密器
Cipher cipher = (algorithm);
(Cipher.DECRYPT_MODE, key, paramSpec);
// 解密数据
byte[] ciphertext = "密文".getBytes(StandardCharsets.UTF_8);
byte[] plaintext = (ciphertext);
// 输出解密后的明文
("明文:" + new String(plaintext, StandardCharsets.UTF_8));
}
}
```
本文介绍了如何使用 Java 中的 包进行 AES 加密和解密。AES 是一种强大的加密算法,可用于保护敏感数据。了解如何使用 AES 加密和解密数据对于保护应用程序中的敏感信息至关重要。
2024-11-12
Java数组元素:从基础到高级操作的深度解析
https://www.shuihudhg.cn/134539.html
PHP Web应用的安全基石:全面解析数据库SQL注入防御
https://www.shuihudhg.cn/134538.html
Python函数入门到进阶:用简洁代码构建高效程序
https://www.shuihudhg.cn/134537.html
PHP中解析与提取代码注释:DocBlock、反射与AST深度探索
https://www.shuihudhg.cn/134536.html
Python深度解析与高效处理.dat文件:从文本到二进制的实战指南
https://www.shuihudhg.cn/134535.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html