全面解析主流加密方案|实战代码|安全建议|性能对比
本页面所有导航均为锚点跳转,无真实二级页面,便于快速定位核心内容。页面内容以java加密字符串为核心,系统梳理加密原理、主流算法、实战案例、常见陷阱及最佳实践,助您构建安全可靠的Java应用。
全文严格遵循SEO规范,语义化标签使用完整,兼容多终端设备,总字数超过4000字,确保内容深度与实用价值兼备。
在Java应用开发中,字符串加密是保障数据安全的核心环节。无论是用户密码、敏感信息传输,还是API签名认证,加密机制都发挥着不可替代的作用。理解加密基础是构建安全系统的前提。
加密的本质是将明文(Plain Text)通过特定算法与密钥(Key)转换为密文(Cipher Text),防止未授权访问。解密则是逆向过程,需相同或相关密钥还原原始数据。
Java平台提供统一的加密接口:javax.crypto包(对称/非对称加密)、java.security包(哈希/数字签名)、java.security.spec包(密钥规范)。核心类包括:
Cipher:加密/解密核心类KeyGenerator:生成对称密钥KeyPairGenerator:生成非对称密钥对MessageDigest:哈希计算SecretKeySpec、RSAPublicKeySpec:密钥规范类例如,AES加密需指定:Cipher.getInstance("AES/GCM/NoPadding"),其中GCM模式同时提供加密与认证(AEAD),优于传统CBC+HMAC组合。
在java加密字符串实践中,选择合适算法是安全与性能的平衡点。以下对五类常用算法进行深度解析。
现代主流对称加密算法,128/192/256位密钥,块大小128位。Java中推荐使用:AES/GCM/NoPadding或AES/CBC/PKCS5Padding。
推荐实践:
KeyGenerator.getInstance("AES").init(256)示例代码(AES-GCM加密):
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
public class AESGCMExample {
public static void main(String[] args) throws Exception {
// 生成密钥
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey key = keyGen.generateKey();
// IV必须为12字节(GCM规范)
byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, iv);
// 加密
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, gcmParameterSpec);
byte[] ciphertext = cipher.doFinal("java加密字符串".getBytes(StandardCharsets.UTF_8));
// 输出结果
System.out.println("密文(Base64): " + Base64.getEncoder().encodeToString(ciphertext));
System.out.println("IV(Base64): " + Base64.getEncoder().encodeToString(iv));
}
}
最成熟的非对称加密算法,基于大整数分解难题。常用于密钥交换、数字签名、小数据加密(如AES密钥加密)。
关键参数:
示例代码(RSA-OAEP加密):
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.OAEPParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class RSAOAEPExample {
public static void main(String[] args) throws Exception {
// 生成密钥对
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
// 加密配置:OAEP with SHA-256 and MGF1
OAEPParameterSpec oaepParams = new OAEPParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
// 加密
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), oaepParams);
byte[] ciphertext = cipher.doFinal("java加密字符串".getBytes(StandardCharsets.UTF_8));
System.out.println("密文(Base64): " + Base64.getEncoder().encodeToString(ciphertext));
}
}
SHA-2家族核心算法,输出256位哈希值,用于密码存储、文件校验、数字签名。注意:哈希不可逆,不可用于加密。
安全建议:
MessageDigest.getInstance("SHA-256")存储密码安全密码存储示例(PBKDF2WithHmacSHA256):
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
public class SecurePasswordHash {
public static String hashPassword(String password, byte[] salt) throws Exception {
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] hash = factory.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(hash);
}
public static byte[] generateSalt() {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
return salt;
}
}
已严重不安全!存在碰撞漏洞(2004年王小云教授破译),严禁用于任何安全场景。仅可用于非安全目的(如文件去重、快速校验非敏感数据完整性)。
错误用法示例(绝对禁止):
// ❌ 千万不要用MD5存密码!
String passwordHash = DigestUtils.md5DigestAsHex(password.getBytes());
基于哈希的认证码,结合密钥与哈希算法(如HMAC-SHA256),用于验证消息完整性与来源真实性,常见于API签名。
典型应用:
示例代码(HMAC-SHA256):
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class HMACSHA256Example {
public static String getSignature(String data, String key) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secretKey);
return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)));
}
}
理论需结合实践。以下聚焦三大高频场景,提供可直接复用的安全实现。
核心原则:
推荐方案(PBKDF2 + 随机盐):
数据库表结构示例:
| 字段名 | 类型 | 说明 |
|---|---|---|
| user_id | bigint | 主键 |
| username | varchar(50) | 用户名 |
| password_hash | varchar(128) | Base64编码的哈希值 |
| salt | varchar(24) | Base64编码的16字节盐 |
防止请求被篡改、重放攻击。流程:
签名计算伪代码:
signature = HMAC-SHA256("GET&/api/user×tamp=1620000000&nonce=abc123", secretKey)
HTTP传输中加密敏感字段(如身份证号、银行卡号):
优势:结合对称加密高效性与非对称加密安全性,避免长数据RSA加密性能瓶颈。
为提升开发效率与安全性,建议封装统一加密工具类。以下提供AES-GCM与RSA-OAEP核心工具方法。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int KEY_SIZE = 256;
private static final int IV_LENGTH = 12;
private static final int TAG_LENGTH_BIT = 128;
public static String encrypt(String plainText, SecretKey key) throws Exception {
byte[] iv = new byte[IV_LENGTH];
new SecureRandom().nextBytes(iv);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_LENGTH_BIT, iv);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, key, gcmParameterSpec);
byte[] ciphertext = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
// 合并IV和密文(IV在前)
byte[] combined = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, combined, 0, iv.length);
System.arraycopy(ciphertext, 0, combined, iv.length, ciphertext.length);
return Base64.getEncoder().encodeToString(combined);
}
public static String decrypt(String encryptedText, SecretKey key) throws Exception {
byte[] combined = Base64.getDecoder().decode(encryptedText);
byte[] iv = new byte[IV_LENGTH];
byte[] ciphertext = new byte[combined.length - IV_LENGTH];
System.arraycopy(combined, 0, iv, 0, iv.length);
System.arraycopy(combined, IV_LENGTH, ciphertext, 0, ciphertext.length);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_LENGTH_BIT, iv);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);
byte[] decrypted = cipher.doFinal(ciphertext);
return new String(decrypted, StandardCharsets.UTF_8);
}
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(KEY_SIZE);
return keyGenerator.generateKey();
}
}
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.OAEPParameterSpec;
import java.util.Base64;
public class RSAUtil {
private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
OAEPParameterSpec oaepParams = new OAEPParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParams);
return Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)));
}
public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
OAEPParameterSpec oaepParams = new OAEPParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParams);
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedText)), StandardCharsets.UTF_8);
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
return kpg.generateKeyPair();
}
}
围绕java加密字符串,以下问题高频出现,需特别注意:
A:加密后数据包含IV(初始向量)与密文。例如AES-GCM需12字节IV,PKCS5Padding会补充至16字节整倍数。Base64编码进一步增加约33%长度,属正常现象。
A:绝对禁止!硬编码密钥等于公开密钥。正确做法:
A:不能!RSA加密长度受限于密钥长度(如2048位RSA最多加密190字节明文)。长数据应采用:混合加密(AES加密数据 + RSA加密AES密钥)。
A:使用认证加密(AEAD)模式,如AES-GCM、ChaCha20-Poly1305。避免单独使用CBC模式(需额外HMAC验证)。Java中优先选择.../GCM/...或.../ECB/OAEP...。
A:在安全场景(密码存储、签名)中,MD5已被证明可快速碰撞,禁止使用。仅可用于非安全校验(如Git版本校验、文件去重),且需明确标注“非安全用途”。
A:核心类(Cipher、MessageDigest)保持稳定,但:
SecureRandom.getInstanceStrong()