I have to encrypt an xml file using openssl command line or a C api. The output shall be Base64.
A java programm will be used for decrypting. This programm is provided by the customer and cannot be changed (they are using this code for legacy applications). As you can see in the code below the customer provides a passphrase so the key will be generated using the SecretKeySpec method.
Java code:
// 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;
}
I have tested several commands like:
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
But non of the given outputs is successfuly decrypted using java. For testing purposes I used the given java code for encrypting and the result is of course different than the one from openssl.
Is there a way to use openssl C api or command line to encrypt data so it could be successful decrypted using the given java code?
Java's SecretKeySpec
uses the password ASCII bytes directly as key bytes, while OpenSSL's -pass pass:...
method derives a key from the password using a key derivation function to transform the password into a key in a secure fashion. You can either try to do the same key derivation in Java (which you probably cannot if I interpret your question correctly), or use OpenSSL's -K
option to pass in a key (as hex bytes!) instead of a password.
You can find out how there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With