java 如何解密
解密方法概述
在Java中实现解密通常涉及对称加密(如AES)、非对称加密(如RSA)或哈希算法(如MD5,但哈希不可逆)。以下是常见解密方法的实现示例。
对称加密解密(AES示例)
AES需使用相同的密钥和初始化向量(IV)进行加密和解密。以下为解密代码:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESDecryptor {
public static String decrypt(String encryptedData, String key, String iv) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
参数说明

encryptedData:Base64编码的加密数据。key:16/24/32字节的密钥(对应AES-128/192/256)。iv:16字节的初始化向量(与加密时一致)。
非对称加密解密(RSA示例)
RSA使用私钥解密数据,公钥用于加密:
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RSADecryptor {
public static String decrypt(String encryptedData, String privateKeyStr) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
注意事项

- RSA解密需处理长文本分块(密钥长度限制,如2048位密钥最多解密256字节)。
- 私钥需为PKCS#8格式(
-----BEGIN PRIVATE KEY-----)。
哈希校验(不可逆操作)
哈希算法(如SHA-256)不可解密,但可验证数据一致性:
import java.security.MessageDigest;
import java.util.HexFormat;
public class HashValidator {
public static String hash(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(input.getBytes());
return HexFormat.of().formatHex(hashBytes);
}
}
用途
- 存储密码时比较哈希值(加盐更安全)。
- 验证文件完整性。
其他注意事项
- 密钥管理:避免硬编码密钥,使用环境变量或密钥管理系统。
- 算法选择:优先选择AES-GCM(带认证的加密模式)替代CBC。
- 异常处理:捕获
NoSuchAlgorithmException等异常,确保解密失败时程序健壮性。
通过以上方法,可覆盖大多数Java解密场景。根据实际需求选择对称或非对称加密方案。






