Re: File encryption under PHP

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Paul M Foster wrote:
Folks:

If I wanted to encrypt a file in PHP and then write it out to disk
(one-way encryption, requiring a password), what PHP built-ins might you
recommend to encrypt the contents of the file before writing it out to
disk?

Paul

Here's a very generic mcrypt example.  IANAE
where security is concerned, but from what I've
read, BLOWFISH should be a fairly decent algorithm
for most applications.  This isn't my work, can't
remember whose ... uses 3DES.

KDK


<?php
$plaintext = "Four score and seven years ago";
$cipher = MCRYPT_TRIPLEDES;
$mode = MCRYPT_MODE_ECB;
$rand_src = MCRYPT_DEV_RANDOM; //MCRYPT_DEV_RANDOM
$password = 'Extra secret password';

print ("Plaintext: $plaintext\n");

// OK, let's encrypt the data
$handle = mcrypt_module_open ($cipher, '', $mode, '');
if (!$handle)
die ("Couldn't locate open mcrypt module for '$cipher' algorithm");
$iv_size = mcrypt_enc_get_iv_size ($handle);
$ivector = mcrypt_create_iv ($iv_size, $rand_src);
if (mcrypt_generic_init ($handle, $password, $ivector) == -1)
die ("Error: mcrypt_generic_init() failed.");
$ciphertext = mcrypt_generic ($handle, $plaintext);
mcrypt_generic_end ($handle);

echo "<br> Ciphertext: " . bin2hex ($ciphertext) . "\n";

// Now let's decrypt it
$handle = mcrypt_module_open ($cipher, '', $mode, '');
if (!$handle) die ("Couldn't locate open mcrypt module for '$cipher' algorithm");

if (mcrypt_generic_init ($handle, $password, $ivector) == -1)
   die ("Error: mcrypt_generic_init() failed.");
$plaintext = mdecrypt_generic ($handle, $ciphertext);
mcrypt_generic_end ($handle);

echo "<br> Plaintext: $plaintext\n");
?>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux