1

I'm having problems trying to "translate" some code from JAVA to PHP.

I already tried a lot of functions but nothing is working for me to get the same results on both sides.

JAVA CODE

public static String encrypt(String text, String key, String charset) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(key);
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);

    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] textBytes = text.getBytes(charset);
    byte[] bytes = cipher.doFinal(textBytes);

    return new String(Base64.encodeBase64(bytes), charset);
}

KEY PARAMETER -> "NWelNxflgZ+rjP0bo2gi2Q=="
TEXT PARAMETER -> "I'm a test"
CHARSET PARAMETER -> "UTF-8"
ALGORITHM CONSTANT -> AES

RESULT -> "13vh3qeuc+kN7NvcKwM6pw=="


PHP CODE

function encryptAES($text, $key)
{
    $key = strtohex($key);
    $encrypt = openssl_encrypt($text, 'aes128', $key, OPENSSL_RAW_DATA);
    if (!$encrypt) {
        throw new Exception('AES encryption error');
    }
    return base64_encode($encrypt);
}

function strtohex($x)
{
    $s='';
    foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
    return($s);
}

KEY PARAMETER -> "NWelNxflgZ+rjP0bo2gi2Q=="
TEXT PARAMETER -> "I'm a test"

RESULT -> "Vs5pwAC7PK0fQUQQ+PMhKw=="


Can anyone please give a hand and explain me why it's not working my code?

Thanks a lot guys.

FedeCaceres
  • 158
  • 1
  • 11
  • @RiggsFolly I'm looking to the other question.... it seems to be completely different. I'm not able to now my answer by looking at the question to sent me. – FedeCaceres Apr 03 '19 at 12:32
  • Did you read the bit about `OPENSSL_RAW_DATA` – RiggsFolly Apr 03 '19 at 12:57
  • @RiggsFolly Yes, and it's still not working! Now I'm getting a result that has the correct `strlen`, so I feel I'm closer. But still not the same. I'm editing the question changing that! – FedeCaceres Apr 03 '19 at 13:02

1 Answers1

1

Fixed, the problem was that the strtohex gives you the password to put in the console.

 public static function encryptAES($data, $AES_key)
    {
        $AES_key = base64_decode($AES_key);
        $encrypt = openssl_encrypt($data, 'aes128', $AES_key);
        if (!$encrypt) {
            throw new Exception('AES encryption error');
        }
        return base64_encode($encrypt);
    }

Here it is the result code, it was just converting the key with base64_decode. Thanks you all!

FedeCaceres
  • 158
  • 1
  • 11