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/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.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