Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php - Read file, alterate data, write new file

Tags:

file

php

aes

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?

like image 890
Manitoba Avatar asked May 24 '26 22:05

Manitoba


1 Answers

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.

like image 200
Manitoba Avatar answered May 27 '26 11:05

Manitoba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!