我需要使用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代码成功解密?