...

View Full Version : What to encrypt an uploaded text file



rfresh
11-05-2007, 10: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?

aedrin
11-05-2007, 11: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)?

Etc.

marek_mar
11-06-2007, 12:46 AM
Use the streams.


<?php
$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');
stream_copy_to_stream($this_file, $temp_file);
fclose($this_file);
fclose($temp_file);

print "---------\nFile Contents\n---------\n";
readfile($temp_file_name);
print "\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);
stream_copy_to_stream($my_file, $encrypted_file);

// Close the files.
fclose($encrypted_file);
fclose($my_file);

print "---------\nEncrypted File Contents\n---------\n";
readfile($encrypted_file_name);
print "\n---------\n";

// Delete the unencrypted file.
unlink($temp_file_name);

// 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";
stream_copy_to_stream($my_file, $output);
print "\n---------\n";
fclose($my_file);
fclose($output);

unlink($encrypted_file_name);
?>

247SiteAlert
11-06-2007, 06: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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum