Java 密码学:加密与哈希 – 实用指南

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

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

开始课程

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



密码学是现代应用程序安全的基础。Java 内置了强大且灵活的加密与哈希处理基础设施——Java Cryptography Architecture (JCA) 和 Java Cryptography Extension (JCE)。这些库支持实现对称加密(AES)和非对称加密(RSA),以及密码学哈希(SHA-256)。在本文中,我们将解析关键概念,并编写纯 Java(无第三方依赖)的工作示例。



基本概念与 JCA/JCE 架构

JCA 提供了执行密码学操作的框架。其核心思想是提供者(providers),它们实现具体的算法。默认情况下,JDK 包含 SUN 提供者(用于哈希)和 SunJCE 提供者(用于加密)。主要类位于 javax.crypto 和 java.security 包中。

  • Cipher — 用于加密和解密的主要类。
  • KeyGenerator — 生成对称密钥。
  • KeyPairGenerator — 生成非对称加密的密钥对。
  • MessageDigest — 计算哈希值。
  • SecretKeySpec — 从字节数组表示对称密钥。


对称加密:AES

AES(高级加密标准)是最流行的对称算法。它使用同一个密钥进行加密和解密。推荐使用 GCM 模式(认证加密)或带 PKCS5Padding 的 CBC 模式。以下是使用 AES-256/GCM 加密字符串的示例。



import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.GCMParameterSpec;import java.security.SecureRandom;import java.util.Base64;

public class AESGCMExample { private static final int AES_KEY_SIZE = 256; private static final int GCM_IV_LENGTH = 12; private static final int GCM_TAG_LENGTH = 128;

public static SecretKey generateKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(AES_KEY_SIZE, SecureRandom.getInstanceStrong()); return keyGen.generateKey(); }

public static String encrypt(String plaintext, SecretKey key) throws Exception { byte[] iv = new byte[GCM_IV_LENGTH]; SecureRandom.getInstanceStrong().nextBytes(iv); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv); cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] cipherText = cipher.doFinal(plaintext.getBytes()); byte[] encrypted = new byte[iv.length + cipherText.length]; System.arraycopy(iv, 0, encrypted, 0, iv.length); System.arraycopy(cipherText, 0, encrypted, iv.length, cipherText.length); return Base64.getEncoder().encodeToString(encrypted); }

public static String decrypt(String encryptedData, SecretKey key) throws Exception { byte[] decoded = Base64.getDecoder().decode(encryptedData); byte[] iv = new byte[GCM_IV_LENGTH]; System.arraycopy(decoded, 0, iv, 0, iv.length); byte[] cipherText = new byte[decoded.length - iv.length]; System.arraycopy(decoded, iv.length, cipherText, 0, cipherText.length); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv); cipher.init(Cipher.DECRYPT_MODE, key, spec); return new String(cipher.doFinal(cipherText)); }

public static void main(String[] args) throws Exception { SecretKey key = generateKey()

推荐