2

I've the task to migrate a php code to Java, but I'm not able to decrypt the information as these functions do. I've read many similar messages, but no solution solve the problem.

static function pkcs7_unpad($data) {
    return substr($data, 0, -ord($data[strlen($data) - 1]));
}


static function decrypt($enc_name) {
    $encryption_key = 'secret_key';
    $iv = 'inizialization_vector';

    $name = Encryptation::pkcs7_unpad(openssl_decrypt(
        $enc_name,
        'AES-256-CBC',
        $encryption_key,
        0,
        $iv
    ));
    return $name;
}

UPDATE

Update with encryption code:

static function pkcs7_pad($data, $size) {
    $length = $size - strlen($data) % $size;
    return $data . str_repeat(chr($length), $length);
}

static function encrypt($name) {
    $encryption_key = 'secret_key';
    $iv = 'inizialization_vector';

    $enc_name = openssl_encrypt(
        Encryptation::pkcs7_pad($name, 16), // padded data
        'AES-256-CBC',        // cipher and mode
        $encryption_key,      // secret key
        0,                    // options (not used)
        $iv                   // initialisation vector
    );

    return $enc_name;
}
igarciadev
  • 131
  • 3
  • 11
  • Have a look at [this](https://stackoverflow.com/questions/52038172/how-could-i-decrypt-openssl-in-java). – kelalaka Jan 29 '19 at 09:51
  • That's right, the problem is that it's a code in use, and there's encrypted data that has to be read from Java. – igarciadev Jan 30 '19 at 06:04

1 Answers1

2

The following Java code focus on the encryption-/decryption-part without a sophisticated exception handling etc. You should adapt it to your requirements. Since the PHP-code is the reference, the double padding has to be taken into account. Analogous to the PHP-methods the default and a custom PKCS7-padding are used in the Java-methods (another approach would be to use no default padding (i.e. AES/CBC/NoPadding) but a completely custom padding).

Custom PKCS7-Padding:

private static byte[] addPKCS7Padding(byte[] data, int size) {
    byte pad = (byte)(size - (data.length % size));
    byte[] output = new byte[data.length + pad];
    System.arraycopy(data, 0, output, 0, data.length);
    for (int i = data.length; i < output.length; i++)
        output[i] = (byte)pad;
    return output;
}

Unpadding:

private static byte[] removePKCS7Padding(byte[] data, int size) {
    byte pad = data[data.length - 1];
    byte[] output = new byte[data.length - pad];
    System.arraycopy(data, 0, output, 0, data.length - pad);
    return output;      
}

A possible counterpart for the PHP encrypt-method is:

public static String encrypt(byte[] plainData) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
    byte[] plainDataPKCS7Padded = addPKCS7Padding(plainData, 16); 
    byte[] encryptedData = cipher.doFinal(plainDataPKCS7Padded);  
    return Base64.getEncoder().encodeToString(encryptedData);
}

A possible counterpart for the PHP decrypt-method is:

public static byte[] decrypt(String encodedAndEncryptedData) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
    byte[] encryptedData = Base64.getDecoder().decode(encodedAndEncryptedData);
    byte[] decryptedData = cipher.doFinal(encryptedData);                       
    return removePKCS7Padding(decryptedData, 16);  
}

Test:

public class Cryptography {

    private static byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8);
    private static byte[] iv  = "0123456789012345".getBytes(StandardCharsets.UTF_8);

    public static void main(String[] args) throws Exception {       
        String plainText = "This is a plain text which needs to be encrypted...";
        String encrypedData = encrypt(plainText.getBytes(StandardCharsets.UTF_8));
        System.out.println(encrypedData);
        byte[] decryptedData = decrypt(encrypedData);
        String decryptedText = new String(decryptedData, StandardCharsets.UTF_8);
        System.out.println(decryptedText);      
    }
    ...
}

Output:

cPF/JWAwp8G9xkUhHIMHLaS8WVfJM2UCxf2bphgOuJ6JVBmMFWAc5rwZzS/hNpAUx3+94UEEwXso2v/LkXVeXJmmfSgIaIvc9oDtGDUoQVo=
This is a plain text which needs to be encrypted...

which is equal to the output of the PHP-methods when the same plain text, key and IV are used.

EDIT:

Since AES-256-CBC is used in the PHP-methods, the key-length is 32 byte. The number denotes the key-length in bits (a 16 byte key would be needed for e.g. AES-128-CBC). The PHP-openssl-methods automatically pad too short keys with 0x0-values. In Java this doesn't happen automatically, but has to be implemented explicitly, e.g. with

private static byte[] padKey(byte[] key) {
    byte[] paddedKey = new byte[32];
    System.arraycopy(key, 0, paddedKey, 0, key.length);
    return paddedKey;
}

For a test replace

private static byte[] key = "01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8);

with

private static byte[] shortLengthKey = "012345678".getBytes(StandardCharsets.UTF_8);
private static byte[] key = padKey(shortLengthKey);

where shortLengthKey represents your 9 byte key.

The output is for both, PHP and Java:

CLPqFawQclb9PPOzcKowWBCi2gsaBJPXpl+kbGD8xYmTgL3WOtGUKpAskhXxhU4SKFZheEWiz+xkUEzLsKht3YzL9ZkSTuYtYwaZ0BjuWLM=
This is a plain text which needs to be encrypted...
Topaco
  • 40,594
  • 4
  • 35
  • 62
  • Testing it I've found that the key used is 9 bytes, and an AES key must be 16/32 / .. what can I do to use the key and recover the encrypted information? – igarciadev Jan 30 '19 at 13:24
  • After a few weeks with another project, I have been able to test the solution and it works. Thank you @Topaco. – igarciadev Mar 13 '19 at 11:19