如何在Java中实现CryptoJS.AES.encrypt函数?

riz*_*sky 0 javascript java encryption aes cryptojs

我正在尝试在 java 中实现crypto-js的以下代码以进行加密

let toEncrypt= "my data";
cryptoJs.AES.encrypt(toEncrypt,"apasswordblabla").toString();
Run Code Online (Sandbox Code Playgroud)

这是我的实现(AES/CBC/PKCS7Padding):

public String encrypt(Map<String,Object> param){
try {
            String toEncrypt= objectMapper.writeValueAsString(param);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] saltData = Arrays.copyOfRange(stringToEncrypt.getBytes(StandardCharsets.UTF_8), 8, 16);
            final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, saltData, "apasswordblabla".getBytes(StandardCharsets.UTF_8), md5);
            SecretKeySpec skeySpec = new SecretKeySpec(keyAndIV[0], "AES");
            IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);
            Cipher cipher;
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding",BouncyCastleProvider.PROVIDER_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec,iv);
            byte[] base64Encoded = Base64.getEncoder().encode(cipher.doFinal(toEncrypt.getBytes(StandardCharsets.UTF_8)));
            return new String(base64Encoded);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
                | BadPaddingException | InvalidKeyException
                | JsonProcessingException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            

        }
}
Run Code Online (Sandbox Code Playgroud)

generateIV(int ,int ,int ,byte[] , byte[], MessageDigest) 的实现:

  • 这个方法相当于OpenSSL的EVP_BytesToKey函数,正如我在cryptojs源代码中看到的那样(crypto-js@4.1.1 on file cipher-core.js line 658),AES的默认格式化程序是OpenSSLFormatter
public static byte[][] generateKeyAndIV(int keyLength, int ivLength, int iterations, byte[] salt, byte[] password, MessageDigest md) {

        int digestLength = md.getDigestLength();
        int requiredLength = (keyLength + ivLength + digestLength - 1) / digestLength * digestLength;
        byte[] generatedData = new byte[requiredLength];
        int generatedLength = 0;

        try {
            md.reset();

            // Repeat process until sufficient data has been generated
            while (generatedLength < keyLength + ivLength) {

                // Digest data (last digest if available, password data, salt if available)
                if (generatedLength > 0)
                    md.update(generatedData, generatedLength - digestLength, digestLength);
                md.update(password);
                if (salt != null)
                    md.update(salt, 0, 8);
                md.digest(generatedData, generatedLength, digestLength);

                // additional rounds
                for (int i = 1; i < iterations; i++) {
                    md.update(generatedData, generatedLength, digestLength);
                    md.digest(generatedData, generatedLength, digestLength);
                }

                generatedLength += digestLength;
            }

            // Copy key and IV into separate byte arrays
            byte[][] result = new byte[2][];
            result[0] = Arrays.copyOfRange(generatedData, 0, keyLength);
            if (ivLength > 0)
                result[1] = Arrays.copyOfRange(generatedData, keyLength, keyLength + ivLength);

            return result;

        } catch (DigestException e) {
            throw new RuntimeException(e);

        } finally {
            // Clean out temporary data
            Arrays.fill(generatedData, (byte)0);
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后我尝试在这里解密它 使用

let toDecrypt="[MY ENCRYPTED DATA IN BASE64]"
let decrypted = cryptoJs.AES.decrypt(toDecrypt, "apasswordblabla").toString(cryptoJs.enc.Utf8).toString(); 
console.log(decrypted);
Run Code Online (Sandbox Code Playgroud)

并且它总是无法解密,并出现错误“Malformed utf-8 data”。因此,我的java实现是错误的

我在这里做错了什么?或者如果有任何现成的库可以解决这个问题请建议

mvm*_*vmn 6

OpenSSL 和 CryptoJS 使用的格式是base64("Salted__" + <salt 8 bytes> + <encrypted data>)

以下是产生这种格式结果的代码(重用generateKeyAndIV上面的方法而不进行任何修改):

    public static void main(String args[]) {
        Security.addProvider(new BouncyCastleProvider());
        System.out.println(encrypt());
    }

    public static String encrypt() {
        try {
            String stringToEncrypt = "Hello world 12345";
            String password = "apasswordblabla";
            SecureRandom sr = new SecureRandom();
            byte[] salt = new byte[8];
            sr.nextBytes(salt);
            final byte[][] keyAndIV = generateKeyAndIV(32, 16, 1, salt, password.getBytes(StandardCharsets.UTF_8),
                    MessageDigest.getInstance("MD5"));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", BouncyCastleProvider.PROVIDER_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyAndIV[0], "AES"), new IvParameterSpec(keyAndIV[1]));
            byte[] encryptedData = cipher.doFinal(stringToEncrypt.getBytes(StandardCharsets.UTF_8));
            byte[] prefixAndSaltAndEncryptedData = new byte[16 + encryptedData.length];
            // Copy prefix (0-th to 7-th bytes)
            System.arraycopy("Salted__".getBytes(StandardCharsets.UTF_8), 0, prefixAndSaltAndEncryptedData, 0, 8);
            // Copy salt (8-th to 15-th bytes)
            System.arraycopy(salt, 0, prefixAndSaltAndEncryptedData, 8, 8);
            // Copy encrypted data (16-th byte and onwards)
            System.arraycopy(encryptedData, 0, prefixAndSaltAndEncryptedData, 16, encryptedData.length);
            return Base64.getEncoder().encodeToString(prefixAndSaltAndEncryptedData);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

产生的示例结果是:U2FsdGVkX1/O8jV2bfcM/06DM106oLAzdf7z66/JakGNefts4MftzXquopkxPaDo

使用以下代码在 JSFiddle 中解码:

console.log(CryptoJS.AES.decrypt("U2FsdGVkX1/O8jV2bfcM/06DM106oLAzdf7z66/JakGNefts4MftzXquopkxPaDo", "apasswordblabla").toString(CryptoJS.enc.Utf8));
Run Code Online (Sandbox Code Playgroud)

在浏览器控制台中产生所需的输出: Hello world 12345