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 数据结构源码揭秘:掌握高效编程利器

下一篇:Java 闹钟实现:打造专属时间提醒