1

I am more into PHP and I do not know how to make identical encrypt() method in Java to that in PHP.

My PHP function is:

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

function encrypt($data) {
    $key = "SiadajerSiadajer";
    $iv_size = 16; 
    $iv = openssl_random_pseudo_bytes($iv_size, $strong);
    $encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    $joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));
    $encodedJoinedData = base64_encode($joinedData);
    return $encodedJoinedData; 
}

What will be the identical method in Java, given the fact that I already have padKey() method which is:

private byte[] padKey(byte[] key) {
    byte[] paddedKey = new byte[32];
    System.arraycopy(key, 0, paddedKey, 0, key.length);
    return paddedKey;
}
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • Generate a random 16-byte IV, encrypt the data, prepend the IV to the encrypted data, base64 encode the result. You don't need the bin2hex/hex2bin business in Java, otherwise it's very similar. – President James K. Polk Mar 18 '19 at 13:00
  • Could you post example input / output (plaintext / ciphertext)? I can easily create an answer, but firing up PHP and installing the openssl crypto library takes *much* longer. – Maarten Bodewes Mar 18 '19 at 14:37
  • Take a look at the answer to this question https://stackoverflow.com/questions/55216692/encryption-in-java-while-decryption-method-is-known. Your PHP-encrypt-method corresponds 100% to the java-encrypt-method described there. – Topaco Mar 18 '19 at 14:38
  • 1
    @Topaco I would say you're almost right; there may be an implementation mistake in the PHP code (in my opinion both the mcrypt and openssl libraries of PHP *are* implementation mistakes). – Maarten Bodewes Mar 18 '19 at 14:48

0 Answers0