AES使用java加密openssl解密

我必须使用openssl命令行或C api加密xml文件。 输出应为Base64。

java程序将用于解密。 此程序由客户提供,无法更改(他们将此代码用于遗留应用程序)。 正如您在下面的代码中看到的那样,客户提供了一个密码短语,因此密钥将使用SecretKeySpec方法生成。

Java代码:

// Passphrase private static final byte[] pass = new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0','1', '2', '3', '4', '5' }; public static String encrypt(String Data) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, key); byte[] encVal = c.doFinal(Data.getBytes()); String encryptedValue = new BASE64Encoder().encode(encVal); return encryptedValue; } public static String decrypt(String encryptedData) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding"); c.init(Cipher.DECRYPT_MODE, key); byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData); byte[] decValue = c.doFinal(decordedValue); String decryptedValue = new String(decValue); return decryptedValue; } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(pass, "AES"); return key; } 

我测试了几个命令,如:

  openssl enc -aes-128-ecb -a -salt -in file.xml -out file_enc.xml -pass pass:123456789012345 openssl enc -aes-128-ecb -a -nosalt -in file.xml -out file_enc.xml -pass pass:123456789012345 

但是使用java成功解密了给定输出的非。 出于测试目的,我使用给定的java代码进行加密,结果当然不同于openssl中的结果。

有没有办法使用openssl C api或命令行来加密数据,以便使用给定的Java代码成功解密?

Java的SecretKeySpec直接使用密码ASCII字节作为关键字节,而OpenSSL的-pass pass:...方法使用密钥派生函数从密码导出密钥,以便以安全的方式将密码转换为密钥。 您可以尝试在Java中执行相同的密钥派生(如果我正确地解释您的问题,您可能不会这样做),或者使用OpenSSL的-K选项传入密钥(作为hex字节!)而不是密码。