java 如何解密
解密方法概述
在Java中实现解密通常涉及对称加密(如AES)、非对称加密(如RSA)或哈希算法(如SHA-256)。具体方法取决于加密时使用的算法和密钥管理方式。
对称加密解密(以AES为例)
对称加密使用相同的密钥进行加密和解密。以下是使用AES解密数据的示例代码:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESDecryptor {
public static String decrypt(String encryptedData, String secretKey) throws Exception {
byte[] keyBytes = secretKey.getBytes("UTF-8");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedBytes = cipher.doFinal(decodedData);
return new String(decryptedBytes, "UTF-8");
}
}
关键点:
- 密钥(
secretKey)必须与加密时使用的相同。 - 使用
Base64解码加密数据(假设加密结果已Base64编码)。 - 模式(如ECB、CBC)和填充方式(如PKCS5Padding)需与加密时一致。
非对称加密解密(以RSA为例)
非对称加密使用公钥加密、私钥解密。以下是RSA解密的示例:
import javax.crypto.Cipher;
import java.security.PrivateKey;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class RSADecryptor {
public static String decrypt(String encryptedData, String privateKeyStr) throws Exception {
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[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedBytes = cipher.doFinal(decodedData);
return new String(decryptedBytes, "UTF-8");
}
}
注意事项:
- 私钥需以PKCS#8格式提供(Base64编码的PEM文件需去除头尾标记)。
- RSA对数据长度有限制,通常用于加密对称密钥而非大数据。
哈希验证(如SHA-256)
哈希算法不可逆,但可用于验证数据完整性。示例:
import java.security.MessageDigest;
import java.util.HexFormat;
public class HashValidator {
public static boolean verifyHash(String data, String expectedHash) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(data.getBytes("UTF-8"));
String actualHash = HexFormat.of().formatHex(hashBytes);
return actualHash.equals(expectedHash);
}
}
用途:
- 校验下载文件或密码存储(需加盐)。
其他注意事项
- 密钥安全:避免硬编码密钥,使用密钥管理服务(如AWS KMS)。
- 算法选择:优先选择AES-GCM( authenticated encryption )而非ECB模式。
- 异常处理:捕获
NoSuchAlgorithmException、InvalidKeyException等异常。
如需更复杂的场景(如混合加密),可结合对称和非对称加密(例如用RSA加密AES密钥)。







