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.