I'm trying to create a kind of file generator in Php. Basically, it get a default file, read data, decrypt the data (Encrypted in AES), encrypt the data with the user password and paste all these bytes into a new file with the client name.
This sould be easy but I got some problems. Here is my current code:
// Load the original raw file
$data = file_get_contents('default.bin');
if (!$data) exit();
// Decrypt the raw data with the default key
$data = AESDecrypt($data, 'default_16_b_key');
// Encrypt the raw data with the user key
$data = AESEncrypt(pad($data, 16), $user_key);
$fileName = sprintf('client_%s.bin', $client_name);
file_put_contents($fileName, $data);
Here are the functions I'm using:
function AESEncrypt($data, $key)
{
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB);
}
function AESDecrypt($data, $key)
{
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB);
}
function pad($data, $blocksize)
{
$pad = $blocksize - (strlen($data) % $blocksize);
return $data . str_repeat(chr($pad), $pad);
}
The AES functions work well as I can decrypt and encrypt a simple string. The pad function seems to do its job to.
The problem is when I try to execute the generated file (which is a jar file after being renamed), I got this message "Unexpected file end" and nothing into my jar file except a blank file (0 byte).
Could you help me to solve this?
Finally, I solved it without using the first decryption. It's possible to encrypt the raw data using the following code:
$data = AESEncrypt(pad($data, 16), $user_key);
You can put that line in an infinite loop (no really infinite btw) and this will still work. Then you can decrypt it in the language of your choice.
Thanks.
jar
files are zipped archives. Use the zip
extension to create a zip file. Remember to rename it to .jar
(or .bin
)
I'm not sure if this is the solution but I had some issues with an ecnrypted string which was solved by base64encoding it. You could give it a try :-)