Java 密码学:加密与哈希——完整指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Java 密码学:加密与哈希——详细指南



在现代信息安全世界中,密码学是保护数据的基石。Java 通过 javax.crypto 和 java.security 包提供了强大的内置工具来实现加密和哈希。在本文中,我们将详细讨论 Java 中的主要密码学操作:对称和非对称加密、密码哈希以及数字签名。



1. Java 密码学基础

Java 密码体系结构(JCA)是一个框架,允许开发人员轻松集成密码学算法。关键类包括:

  • javax.crypto.Cipher — 用于加密和解密。
  • java.security.MessageDigest — 用于哈希。
  • java.security.KeyPairGenerator — 用于生成密钥。
  • javax.crypto.spec.SecretKeySpec — 用于创建对称密钥。

要使用密码学,请导入:

import javax.crypto.*;import javax.crypto.spec.*;import java.security.*;


2. 对称加密(AES)

对称加密使用同一个密钥进行加密和解密。AES(高级加密标准) 是最流行的算法。字符串加密示例:

import javax.crypto.*;import javax.crypto.spec.*;import java.util.Base64;

public class AesExample { public static void main(String[] args) throws Exception { String plainText = "秘密消息"; String secretKey = "0123456789abcdef"; // AES-128 需要 16 字节

// 创建密钥 SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

// 加密 cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes); System.out.println("加密后: " + encryptedText);

// 解密 cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); System.out.println("解密后: " + decryptedText); }}

重要提示: 不建议对大量数据使用 ECB 模式。请使用 AES/GCM/NoPadding 以获得更好的安全性。



3. 非对称加密(RSA)

非对称加密使用一对密钥:公钥(用于加密)和私钥(用于解密)。RSA 是经典算法。示例:

import javax.crypto.*;import java.security.*;import java.util.Base64;

public class RsaExample { public static void main(String[] args) throws Exception { // 生成密钥对 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); PrivateKey privateKey = pair.getPrivate();

// 使用公钥加密 Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedBytes = cipher.doFinal("秘密数据".getBytes()); String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes); System.out.println("RSA 加密后: " + encryptedText);

// 使用私钥解密 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

推荐