开发者

mcrypt for a complete file encryption

I am using mcrypt like this

<?php
   $iv_size = mcrypt_get_iv_size(MCRYPT_RI开发者_开发问答JNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $key = "This is a very secret key";
   $text = "Meet me at 11 o'clock behind the monument.";
   echo strlen($text) . "\n";

   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
   echo strlen($crypttext) . "\n";
?>

this works fine to encrypt certain text. However now I need to save this to a file and encrypt the complete file. Using php5.


Just a small change will do:

<?php
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
   $key = "This is a very secret key";
   $text = file_get_contents('path/to/your/file');
   echo strlen($text) . "\n";

   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
   file_put_contents('path/to/your/file', $crypttext);   
?>

If indeed the file is too big, break it into blocks that are multiple of 128 and do the encryption on each of them.


The easiest solution is to just read the file in, perform the encryption, then write the file back out.

This will run into memory issues if you are dealing with very large files, but for small ones it allows you to do this without needing any additional code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜