当前位置: 首页 > news >正文

Java 加密与解密:从算法到应用的全面解析

Java 加密与解密:从算法到应用的全面解析

一、加密与解密技术概述

在当今数字化时代,数据安全至关重要。Java 加密与解密技术作为保障数据安全的关键手段,被广泛应用于各个领域。

加密是将明文数据通过特定算法转换为密文,使得即使数据被截获,攻击者也难以获取原始信息。而解密则是加密的逆过程,将密文还原为明文。

二、Java 中的对称加密算法

(一)AES 算法

AES(高级加密标准)是一种对称加密算法,具有高效、安全的特点,在 Java 中应用广泛。

  • 代码实例
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;public class AESExample {public static void main(String[] args) throws Exception {// 生成密钥KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");keyGenerator.init(128); // 初始化密钥长度SecretKey secretKey = keyGenerator.generateKey();byte[] keyBytes = secretKey.getEncoded();// 加密String plainText = "hello,world";Cipher cipher = Cipher.getInstance("AES");SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);System.out.println("加密后的文本:" + encryptedText);// 解密cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));String decryptedText = new String(decryptedBytes);System.out.println("解密后的文本:" + decryptedText);}
}
  • 原理分析 :通过 KeyGenerator 生成 AES 密钥,利用 Cipher 类进行加密和解密操作,其中 SecretKeySpec 用于将密钥字节数组转换为密钥规范对象。

(二)DES 算法

DES(数据加密标准)是一种较早的对称加密算法,虽然安全性相对较低,但在一些遗留系统中仍有应用。

  • 代码实例
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.spec.KeySpec;
import java.util.Base64;public class DESExample {public static void main(String[] args) throws Exception {// 定义密钥String key = "12345678"; // DES 密钥长度必须为 8 字节// 加密String plainText = "hello,world";DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, secretKey);byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);System.out.println("加密后的文本:" + encryptedText);// 解密cipher.init(CipherEC.DRYPT_MODE, secretKey);byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));String decryptedText = new String(decryptedBytes);System.out.println("解密后的文本:" + decryptedText);}
}
`` `* **原理分析** :使用 `DESKeySpec` 定义 DES 密钥规范,通过 `SecretKeyFactory` 将其转换为密钥对象,再利用 `Cipher` 实现加密和解密。## 三、Java 中的非对称加密算法### (一)RSA 算法RSA 是一种典型的非对称加密算法,基于大整数因式分解的数学难题,具有较高的安全性,在身份认证、数字签名等方面应用广泛。* **代码实例** :
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import javax.crypto.Cipher;
import java.util.Base64;public class RSAExample {public static void main(String[] args) throws Exception {// 生成密钥对KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(2048); // 初始化密钥长度KeyPair keyPair = keyPairGenerator.generateKeyPair();PublicKey publicKey = keyPair.getPublic();PrivateKey privateKey = keyPair.getPrivate();// 加密String plainText = "hello,world";Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);System.out.println("加密后的文本:" + encryptedText);// 解密cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));String decryptedText = new String(decryptedBytes);System.out.println("解密后的文本:" + decryptedText);// 数字签名String message = "签署的文本";Signature signature = Signature.getInstance("SHA256withRSA");signature.initSign(privateKey);signature.update(message.getBytes());byte[] signedBytes = signature.sign();String signedText = Base64.getEncoder().encodeToString(signedBytes);System.out.println("数字签名:" + signedText);// 验证签名Signature signatureVerify = Signature.getInstance("SHA256withRSA");signatureVerify.initVerify(publicKey);signatureVerify.update(message.getBytes());boolean verifyResult = signatureVerify.verify(Base64.getDecoder().decode(signedText));System.out.println("验证签名结果:" + verifyResult);}
}
  • 原理分析 :通过 KeyGeneratorPair 生成公私密钥对,使用公钥进行加密,私钥进行解密;在数字签名中,使用私钥对消息进行签名,公钥用于验证签名的合法性。

四、Java 中的哈希算法

哈希算法将任意长度的数据映射为固定长度的哈希值,具有单向性,可用于数据完整性校验、密码存储等。

(一)MD5 算法

MD5 是一种常用的哈希算法,虽然其安全性存在一定的缺陷,但在一些简单场景下仍有应用。

  • 代码实例
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class MD5Example {public static void main(String[] args) {String plainText = "hello,world";try {MessageDigest md5 = MessageDigest.getInstance("MD5");byte[] hashBytes = md5.digest(plainText.getBytes());StringBuilder hexString = new StringBuilder();for (byte b : hashBytes) {String hex = Integer.toHexString(b & 0xFF);if (hex.length() == 1) {hexString.append('0');}hexString.append(hex);}System.out.println("MD5 哈希值:" + hexString.toString());} catch (NoSuchAlgorithmException e) {e.printStackTrace();}}
}
  • 原理分析 :使用 MessageDigest 类获取 MD5 算法实例,对输入数据进行哈希运算,将得到的字节数组转换为十六进制字符串表示哈希值。

(二)SHA 算法

SHA(安全哈希算法)是一组更强的哈希算法,如 SHA - 1、SHA - 256 等,具有更高的安全性。

  • 代码实例
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class SHAExample {public static void main(String[] args) {String plainText = "hello,world";try {MessageDigest sha256 = MessageDigest.getInstance("SHA-256");byte[] hashBytes = sha256.digest(plainText.getBytes());StringBuilder hexString = new StringBuilder();for (byte b : hashBytes) {String hex = Integer.toHexString(b & 0xFF);if (hex.length() == 1) {hexString.append('0');}hexString.append(hex);}System.out.println("SHA-256 哈希值:" + hexString.toString());} catch (NoSuchAlgorithmException e) {e.printStackTrace();}}
}
  • 原理分析 :与 MD5 类似,通过 MessageDigest 获取 SHA - 256 算法实例,对输入数据进行哈希运算并转换为十六进制字符串表示。

五、Java 加密与解密的应用场景

(一)数据加密传输

在互联网通信中,使用对称加密算法如 AES 对数据进行加密,再通过非对称加密算法如 RSA 对对称密钥进行加密传输,确保数据在传输过程中的安全性。

(二)敏感信息存储

对于密码、身份证号等敏感信息,可采用哈希算法如 SHA - 256 进行存储,验证时将输入信息进行哈希运算并与存储的哈希值进行比对。

(三)数字签名与身份认证

在电子文档、软件更新等领域,使用非对称加密算法实现数字签名,通过私钥对数据进行签名,公钥验证签名,确保数据的完整性和来源的可靠性。

在这里插入图片描述

相关文章:

  • 深入解析 Linux 系统中库的加载机制:从静态链接到动态运行时
  • 序章:写在前面
  • 进行网页开发时,怎样把function()中变量值在控制台输出,查看?
  • 意见反馈留言二维码制作
  • neo4j中节点内的名称显示不全解决办法(如何让label在节点上自动换行)
  • Discuz!与DeepSeek的AI融合:打造智能网址导航新体验——以“虎跃办公”为例
  • 树莓派超全系列教程文档--(42)树莓派config.txt旧版配置HDMI和杂项选项
  • Javase 基础入门 —— 04 继承
  • 大模型应用相关问题记录
  • 嵌入式系统调用底层基本原理分析
  • 【EasyPan】removeFile2RecycleBatch方法及递归操作解析
  • 香港服务器租用需要哪些性能要求
  • 基于STM32_HAL库的HC-08蓝牙插座项目
  • 1.2、AI及LLM基础:OpenAI 开发
  • 知识储备-后仿
  • 木马派RV1106G3开发板驱动AIC8800DC USB WiFi模块
  • 若依框架深度解析:企业级快速开发平台的设计哲学与实践
  • SwiftUI 1.Text介绍和使用
  • 基于缺失数据的2024年山东省专项债发行报告
  • Linux进程状态及转换关系
  • 五矿地产:今年要确保债务“不爆雷”、交付“不烂尾”
  • 国家市场监管总局:民生无小事,严打民生领域侵权假冒违法行为
  • 马上评丨一些影视剧的片名,越来越让人看不懂
  • 中国海警登临铁线礁开展维权行动并展示五星红旗
  • 魔都眼·上海车展④|奔驰宝马保时捷……全球豪车扎堆首秀
  • 读图丨漫游者秦龙,一生为经典画插图