I'm using phplibsec to do some encryption operations. The library has a method to set the IV and I'm using it to generate a random initialization vector to use in encrypt operations. The problem is that I need to have the same IV to decrypt the data (I didn't know this aspect). Now after small code modification I want to prepend the generated IV to the encrypted data but I don't know how to proceed.
encrypt.php
use phpseclib\Crypt\AES;
use phpseclib\Crypt\Random;
$payload = [];
// new phpseclib AES instance
$cipher = new AES();
// set a password for the encrypt
$cipher->setPassword($password);
// IV creation
$iv = Random::string($cipher->getBlockLength() >> 3);
// this method of the library will make the forst part of my data unreadable without iv
$cipher->setIV($iv);
// encrypt data - here I want to prepend the iv to get it later on decrypt
$output = $cipher->encrypt("some data");
// push encrypted data into an array
array_push($payload, $output);
decrypt.php
use phpseclib\Crypt\AES;
use phpseclib\Crypt\Random;
$cipher = new AES();
$cipher->setPassword($password);
// here is my mistake - I'm creating a new IV but I need the same
$cipher->setIV(Random::string($cipher->getBlockLength() >> 3));
// opening the file that hold encrypted data
$payload = file_get_contents('myencrypted.file');
// I've used the : to separate each line of encrypted data with php implode()
$exploded = explode(' : ', $payload);
// iterating over the array that hold encrypted data to decrypt them then base64_encode before pass back to the client in json.
foreach( $exploded as $str ){
array_push($output, base64_encode($cipher->decrypt($str) ));
}
The decrypt operation will give me something similar (I'm encrypting images data uri)
XGG”)”>hÑÏÄr*‹base64,/9j/4AAQSkZJRgABAgAAAQABAAD…D8
I think that this part XGG”)”>hÑÏÄr*‹
of the decrypted data is the IV?
How I can prepend or append it to the encrypted data and then extrac it when the data needs to be decrypted?Can anyone help me please?
UPDATE
I've followed the suggestion of Topaco in comments and now I'm able to get back the data uri but it will have the iv attached so I need to remove it. At the moment after decrypt the data uri will have this structure:
¸ÈouFH@¬ÆÌ~k!Eâdata:image/jpeg;base64,/9j/4AAQSk
How I will remove the part before the data:image/jpeg;base64 ?