本文旨在解决java后端解密由cryptojs(javascript)加密的openssl格式数据时遇到的兼容性问题。核心在于理解cryptojs将字符串密钥视为密码,并利用openssl的`evp_bytestokey()`函数通过密码和盐值派生出实际的aes密钥和iv。教程将详细指导如何在java中通过解析密文中的盐值,并借助bouncycastle库实现密钥派生和aes/cbc/pkcs7padding解密,确保跨语言数据安全传输的正确性。
在使用CryptoJS进行加密时,如果将一个字符串作为key参数传递给CryptoJS.AES.decrypt或CryptoJS.AES.encrypt方法,CryptoJS并不会直接将其用作AES的对称密钥。相反,它会将其视为一个密码(passphrase)。在这种模式下,CryptoJS会采用OpenSSL的专有密钥派生函数EVP_BytesToKey()来从这个密码和一个随机生成的盐值(salt)中派生出实际的AES密钥(Key)和初始化向量(IV)。
EVP_BytesToKey()函数的工作原理是:它使用MD5哈希算法,将密码和盐值进行多次迭代哈希,以生成足够长度的密钥和IV。为了确保解密端能够正确派生出相同的密钥和IV,加密过程中生成的8字节盐值会被附加到密文的前面。CryptoJS生成的这种OpenSSL格式的密文通常以Base64编码,其原始字节结构为:
Salted__ (ASCII编码,8字节前缀) + Salt (8字节随机盐值) + Ciphertext (实际密文)
因此,当Java后端尝试解密此类数据时,不能简单地将原始密钥字符串截取后直接用作AES密钥和IV。这会导致BadPaddingException等错误,因为Java的javax.crypto默认不执行EVP_BytesToKey()这样的密钥派生过程,也无法识别密文中的Salted__前缀和盐值。
要在Java中正确解密CryptoJS生成的OpenSSL格式加密数据,需要遵循以下三个核心步骤:
首先,需要从CryptoJS返回的Base64编码字符串中解析出Salted__前缀、8字节的盐值以及实际的密文。
由于Java标准库不提供EVP_BytesToKey()的实现,我们需要引入第三方加密库,如BouncyCastle。BouncyCastle提供了一个OpenSSLPBEParametersGenerator,可以模拟EVP_BytesToKey()的行为。
在获得派生出的密钥和IV后,即可使用BouncyCastle的AES实现进行解密。
以下是一个完整的Java示例代码,演示如何使用BouncyCastle库解密CryptoJS生成的OpenSSL格式加密数据。
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.ParametersWithIV; import org.bouncycastle.crypto.params.KeyParameter; // 用于获取派生出的密钥 public class CryptoJsAesDecryptor { public static String decryptCryptoJsOpenSslFormat(String encryptedBase64Token, String passwordStr) throws Exception { // 1. 提取盐值与密文 byte[] saltCiphertext = Base64.getDecoder().decode(encryptedBase64Token); ByteBuffer byteBuffer = ByteBuffer.wrap(saltCiphertext); // 验证并跳过"Salted__"前缀 byte[] prefix = new byte[8]; byteBuffer.get(prefix); if (!new String(prefix, StandardCharsets.US_ASCII).equals("Salted__")) { throw new IllegalArgumentException("Invalid CryptoJs OpenSSL format: missing 'Salted__' prefix."); } // 提取盐值 (8字节) byte[] salt = new byte[8]; byteBuffer.get(salt); // 提取实际密文 byte[] ciphertext = new byte[byteBuffer.remaining()]; byteBuffer.get(ciphertext); // 2. 密钥与IV派生 (使用BouncyCastle的OpenSSLPBEParametersGenerator) byte[] password = passwordStr.getBytes(StandardCharsets.UTF_8); OpenSSLPBEParametersGenerator pbeGenerator = new OpenSSLPBEParametersGenerator(new MD5Digest()); pbeGenerator.init(password, salt); // 对于AES-256,密钥大小为256位,IV大小为128位 // 注意:CryptoJS的keySize参数在字符串密码模式下,可能不直接代表最终密钥大小, // OpenSSL EVP_BytesToKey通常为AES派生256位密钥和128位IV。 ParametersWithIV parameters = (ParametersWithIV) pbeGenerator.generateDerivedParameters(256, 128); // 可选:获取派生出的密钥和IV,用于调试或进一步验证 // byte[] derivedKey = ((KeyParameter)parameters.getParameters()).getKey(); // byte[] derivedIV = parameters.getIV(); // 3. 执行AES解密 (使用BouncyCastle) // 使用AES引擎,CBC模式,PKCS7填充 PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); cipher.init(false, parameters); // false表示解密模式 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字符串 return new String(plaintext, 0, length, StandardCharsets.UTF_8); } public static void main(String[] args) { String token = "U2FsdGVkX1+6YueVRKp6h0dZfk/a8AC9vyFfAjxD4nb7mXsKrM7rI7xZ0OgrF1sShHYNLMJglz4+67n/I7P+fg=="; String key = "p80a0811-47db-2c39-bcdd-4t3g5h2d5d1a"; // 对应CryptoJS中的password try { String decryptedString = decryptCryptoJsOpenSslFormat(token, key); System.out.println("Decrypted Token: " + decryptedString); // 预期输出: {"name":"Burak","surName":"Bayraktaroglu"} } catch (Exception e) { System.err.println("Error during decryption: " + e.getMessage()); e.printStackTrace(); } } }
org.bouncycastle bcprov-jdk15on1.70
并且可能需要在使用前注册BouncyCastle提供者:Security.addProvider(new BouncyCastleProvider());。不过,在上述示例代码中,直接使用BouncyCastle的API,通常不需要显式注册。