
本文旨在解决CryptoJS在JavaScript中采用字符串密钥进行AES解密时,其默认的OpenSSL EVP_BytesToKey密钥派生机制在Java中实现等效解密的问题。通过详细阐述CryptoJS的密钥处理方式,并提供基于BouncyCastle库的Java实现方案,指导开发者正确提取盐值和密文,并使用EVP_BytesToKey算法派生密钥和IV,最终成功解密数据。
在跨平台加密解密场景中,尤其是在JavaScript前端使用CryptoJS加密,后端Java进行解密时,开发者常会遇到因密钥派生机制不一致导致的解密失败问题。本文将深入探讨CryptoJS处理字符串密钥的特殊行为,并提供一个在Java中实现等效解密的专业教程,重点介绍如何利用BouncyCastle库来解决这一挑战。
当CryptoJS的CryptoJS.AES.decrypt方法接收一个字符串作为密钥(而非预先处理好的WordArray对象)时,它不会直接将该字符串用作AES密钥。相反,它会将该字符串视为一个“密码”(password),并结合一个随机生成的8字节“盐值”(salt),通过OpenSSL专有的EVP_BytesToKey()函数来派生出实际用于AES加密的密钥(key)和初始化向量(IV)。
这种密钥派生过程的特点是:
立即学习“Java免费学习笔记(深入)”;
由于Java标准库javax.crypto没有内置EVP_BytesToKey()的实现,直接将CryptoJS的字符串密钥用于Java的SecretKeySpec和IvParameterSpec会导致BadPaddingException或密钥长度错误,因为Java无法正确地从原始字符串“密码”中派生出与CryptoJS一致的密钥和IV。
要在Java中成功解密CryptoJS生成的密文,需要遵循以下三个核心步骤:
鉴于EVP_BytesToKey()算法的复杂性及其在Java标准库中的缺失,我们强烈推荐使用BouncyCastle这样的第三方加密库。BouncyCastle提供了可靠的OpenSSLPBEParametersGenerator,能够准确地实现EVP_BytesToKey()功能。
首先,确保您的Java项目中已添加BouncyCastle依赖。如果您使用Maven,可以在pom.xml中添加:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version> <!-- 或更高版本 -->
</dependency>接下来,我们将详细展示如何使用BouncyCastle实现上述解密过程。
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class CryptoJsAesDecryptor {
public static String decryptCryptoJsAes(String encryptedBase64Token, String passwordStr) throws Exception {
// 1. 从Base64编码的密文中提取盐值和实际密文
// CryptoJS生成的密文格式为:Base64(Salted__ + salt + ciphertext)
byte[] saltCiphertext = Base64.getDecoder().decode(encryptedBase64Token);
ByteBuffer byteBuffer = ByteBuffer.wrap(saltCiphertext);
// 验证前缀是否为 "Salted__"
byte[] prefix = new byte[8];
byteBuffer.get(prefix);
String prefixStr = new String(prefix, StandardCharsets.US_ASCII);
if (!"Salted__".equals(prefixStr)) {
throw new IllegalArgumentException("Invalid CryptoJs encrypted token format: missing 'Salted__' prefix.");
}
// 提取8字节的盐值
byte[] salt = new byte[8];
byteBuffer.get(salt);
// 提取剩余的实际密文
byte[] ciphertext = new byte[byteBuffer.remaining()];
byteBuffer.get(ciphertext);
// 2. 使用OpenSSL EVP_BytesToKey() 算法派生密钥和IV (通过BouncyCastle实现)
byte[] password = passwordStr.getBytes(StandardCharsets.UTF_8);
// OpenSSLPBEParametersGenerator 实现了 EVP_BytesToKey 算法
// CryptoJs默认使用MD5作为哈希函数
OpenSSLPBEParametersGenerator pbeGenerator = new OpenSSLPBEParametersGenerator(new MD5Digest());
// 初始化生成器,传入密码和盐值
pbeGenerator.init(password, salt);
// 生成派生参数:256位密钥 (32字节), 128位IV (16字节)
// 注意:AES-256需要256位密钥,CBC模式需要128位IV
ParametersWithIV parameters = (ParametersWithIV) pbeGenerator.generateDerivedParameters(256, 128);
// 可以通过以下方式获取派生出的密钥和IV,但通常直接传递parameters对象给cipher即可
// byte[] derivedKey = ((KeyParameter)parameters.getParameters()).getKey();
// byte[] derivedIV = parameters.getIV();
// 3. 使用派生出的密钥和IV进行AES解密 (通过BouncyCastle实现)
// 创建一个带有填充的块密码,使用CBC模式和AES引擎
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
// 初始化解密器:false表示解密模式,parameters包含密钥和IV
cipher.init(false, parameters); // false for decrypt mode
// 创建一个足够大的缓冲区来存储解密后的明文
byte[] plaintext = new byte[cipher.getOutputSize(ciphertext.length)];
// 处理密文数据
int length = cipher.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0);
// 完成解密过程,处理任何剩余的字节并移除填充
length += cipher.doFinal(plaintext, length);
// 将解密后的字节数组转换为UTF-8字符串
String plaintextStr = new String(plaintext, 0, length, StandardCharsets.UTF_8);
return plaintextStr;
}
public static void main(String[] args) {
String token = "U2FsdGVkX1+6YueVRKp6h0dZfk/a8AC9vyFfAjxD4nb7mXsKrM7rI7xZ0OgrF1sShHYNLMJglz4+67n/I7P+fg==";
String key = "p80a0811-47db-2c39-bcdd-4t3g5h2d5d1a";
try {
String decryptedData = decryptCryptoJsAes(token, key);
System.out.println("Decrypted Data: " + decryptedData); // 预期输出: {"name":"Burak","surName":"Bayraktaroglu"}
// 如果解密结果是JSON字符串,可以进一步解析
// JSONObject jsonObject = new JSONObject(decryptedData); // 假设使用org.json库
// System.out.println("Name: " + jsonObject.getString("name"));
} catch (Exception e) {
System.err.println("Decryption failed: " + e.getMessage());
e.printStackTrace();
}
}
}通过上述BouncyCastle的实现,您可以在Java后端成功解密由CryptoJS在前端使用字符串密码加密的数据。理解CryptoJS的内部工作机制是解决此类跨平台加密兼容性问题的关键。
以上就是Java中实现CryptoJS AES解密的等效方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号