Java 中的字符串加密与解密350
在计算机系统中,字符串数据的安全性和保密性至关重要。Java 编程语言提供了多种机制,允许我们对字符串进行加密和解密,从而保护其免受未经授权的访问和修改。
加密
加密是一个将可读数据转换为不可读格式的过程,称为密文。Java 中有几种常见的加密算法,包括:
AES (高级加密标准)
DES (数据加密标准)
RSA (Rivest-Shamir-Adleman)
SHA (安全散列算法)
以下代码示例演示了如何使用 AES 算法对字符串进行加密:```java
import ;
import ;
public class EncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
// 生成一个 128 位的 AES 密钥
byte[] key = "mySecret12345678".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
// 创建一个 cipher 对象并初始化为加密模式
Cipher cipher = ("AES");
(Cipher.ENCRYPT_MODE, keySpec);
// 加密字符串
byte[] cipherText = (());
// 转换密文为十六进制字符串
String encryptedText = toHexString(cipherText);
("加密后的字符串:" + encryptedText);
}
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
(("%02X", b));
}
return ();
}
}
```
解密
解密是将密文转换回可读数据的过程。它使用与加密相同或不同的密钥进行,具体取决于加密算法。
以下代码示例演示了如何使用 AES 算法对加密过的字符串进行解密:```java
import ;
import ;
public class DecryptionExample {
public static void main(String[] args) throws Exception {
String encryptedText = "69799D439E389E51E08A13D02665D251";
// 生成一个 128 位的 AES 密钥
byte[] key = "mySecret12345678".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
// 创建一个 cipher 对象并初始化为解密模式
Cipher cipher = ("AES");
(Cipher.DECRYPT_MODE, keySpec);
// 将十六进制字符串转换为字节数组
byte[] cipherBytes = hexStringToByteArray(encryptedText);
// 解密密文
byte[] plainTextBytes = (cipherBytes);
// 转换为字符串
String plainText = new String(plainTextBytes);
("解密后的字符串:" + plainText);
}
private static byte[] hexStringToByteArray(String hex) {
int length = ();
byte[] bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
bytes[i / 2] = (byte) ((((i), 16)
2024-11-23
上一篇:Java 字符串到数组转换指南
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