I need a token to access some source. The source provider gave me a java example that show me how to create it. Here is how it encrypt text:
private static final String ALGO = "AES";
public static String encrypt(byte[] keyValue, String token_text) throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] bytes = c.doFinal(token_text.getBytes());
byte[] buf = Base64.encodeBase64(bytes);
return new String(buf);
}
I wish to translate this pice of java program to php.So, here is my code:
public static function generate_token($token_text, $key) {
$iv = self::hex_to_str("00000000000000000000000000000000");
$token = openssl_encrypt($token_text, "AES-128-CBC", $key, 0, $iv);
return $token;
}
private static function hex_to_str($hex)
{
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
But I can't get same result. I searched around. It looks like cipher.init called without vector. If i do the same thing to openssl_encrypt, it will gave me an error:
openssl_encrypt(): Using an empty Initialization Vector (iv) is potentially insecure and not recommended
Some one said the default vector for Cipher is 0. I tried so, still can't get the same result, but very close:
java: v8GhW0lu8DzNyqsfQTg4g7H6pwXCAAgy9vqFdz5OmXY=
php : v8GhW0lu8DzNyqsfQTg4g6If77f+8YVCcq8VcQGNe68=
I am stuck here for a whole day. I would be very grateful if anyone can help.
# java -version
openjdk version "1.8.0_101"
OpenJDK Runtime Environment (build 1.8.0_101-b13)
OpenJDK 64-Bit Server VM (build 25.101-b13, mixed mode)
# php -v
PHP 5.6.24 (cli) (built: Jul 21 2016 07:42:08)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies