Reputation: 489
I have a requirement to use AES encryption with specific parameters but the only example provided is in Java. I need to move everything to PHP and I'm not sure how to do it exactly.
In Java the encryption class takes the iv/salt parameters as an array of bytes directly. Something in the likes of:
byte[] iv = {(byte) 0xCB, (byte) 0x35, (byte) 0xF3, (byte) 0x52, (byte) 0x1A, (byte) 0xF7, (byte) 0x38, (byte) 0x0B, (byte) 0x75, (byte) 0x03, (byte) 0x8E, (byte) 0xE0, (byte) 0xEF, (byte) 0x39, (byte) 0x98, (byte) 0xC7};
AlgorithmParameterSpec params = new IvParameterSpec(iv);
but PHP expects a string for input, so I tried to do something like:
private $salt = ['a7', '70', '1f', 'f6', '5e', 'd3', '29', '8f'];
private $iv = ['cb', '35', 'f1', '52', '1b', 'f7', '33', '0b', '75', '03', '8e', 'e0', 'cf', '39', '98', 'c7'];
public function __construct()
{
$iv = implode(array_map("hex2bin", $this->iv));
$this->iv = $iv;
$salt = implode(array_map("hex2bin", $this->salt));
$this->salt = $salt;
}
public function encrypt($unencryptedString)
{
$key = hash_pbkdf2('sha1', $this->passPhrase, $this->salt, $this->iterationCount, $this->keyLen, true);
var_dump($key);
$hash = openssl_encrypt($unencryptedString, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $this->iv);
$encoded = base64_encode($hash);
return $encoded;
}
I imagine I'm not using the iv/salt parameters the same way its used on Java, thats why it doesn't produce the same thing. Suggestions?
Upvotes: 1
Views: 800
Reputation: 489
Following @Luke's suggestion:
Removing 0x and using lower case in all iv/salt values seems to do it.
private $salt = ['a7', '71', '1f', 'f5', '5d', 'd2', '28', '8f'];
Upvotes: 0
Reputation: 3551
You should always Use a standard library for PHP encryption.
I know we shouldn't be making recommendations but encryption is in my opinion somewhat of an exception and you should utilise tried and tested libraries.
Use either the openssl extensions or libsodium
Answers on using both are linked here.
How to encrypt plaintext with AES-256 CBC in PHP using openssl()?
How to encrypt / decrypt AES with Libsodium-PHP
In terms of your implemtation I think the $iv
and $key
aren't well formed inputs for hex2bin()
$iv = ['0xA7', '0x71', '0x1F', '0xF5', '0x5D', '0xD2', '0x28', '0x8F'];
array_map("hex2bin", $iv);
// outputs Warning: hex2bin(): Input string must be hexadecimal string
Upvotes: 1