11-05-2007, 09:51 PM
I want to upload text files to a given website and I would like to encrypt them after they have been uploaded. I've googled around but just don't see a PHP encrypt function that works on files (saw only for data streams) - any suggestions?
11-05-2007, 10:07 PM
You're not giving enough information.
What have you searched for?
Do you need one way or two way encryption?
What are the sizes of the files (can you read them in, encrypt and them save them again)?
11-05-2007, 11:46 PM
Use the streams.
$passphrase = 'secret';
// Generate those as you like.
$iv = substr(md5('iv' . $passphrase, true), 0, 8);
$key = substr(md5('some_salt' . $passphrase, true) . md5($passphrase . 'more_salt', true), 0, 24);
$opts = array(
'iv' => $iv,
'key' => $key
// Create a temporary file so we have soemthing to read from. The file will contain this script.
$temp_file_name = tempnam('', 'encryption_test_');
$temp_file = fopen($temp_file_name, 'wb');
$this_file = fopen(__FILE__, 'rb');
print "---------\nFile Contents\n---------\n";
// Open the file you want to encrypt
$my_file = fopen($temp_file_name, 'rb');
// Open the encrypted file. You will create a new file and copy the contents of your file, encrypted.
$encrypted_file_name = tempnam('', 'encryption_test_');
$encrypted_file = fopen($encrypted_file_name, 'wb');
// Set encryption filter.
stream_filter_append($encrypted_file, 'mcrypt.twofish', STREAM_FILTER_WRITE, $opts);
// Close the files.
print "---------\nEncrypted File Contents\n---------\n";
// Delete the unencrypted file.
// Decrypt file.
$my_file = fopen($encrypted_file_name, 'rb');
stream_filter_append($my_file, 'mdecrypt.twofish', STREAM_FILTER_READ, $opts);
$output = fopen('php://output', 'w');
print "---------\nDecrypted File Contents\n---------\n";
11-06-2007, 05:41 AM
Yes I did think about the stream method. I was hoping there was a function that would just work on a file itself but it looks like I will have to go with using the stream method.
I do need to encrypt the file and then decrypt it - I'll come up with a stream method and reference your code example - thanks.