0

I am using mcrypt like this

<?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 = "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.

1
  • ECB mode is EVIL, do not use it as it will encode every block in the same way and thus give clue to what could be in the file Commented Jan 5, 2011 at 21:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

30 Warning: file_put_contents(test.txt): failed to open stream: Permission denied in test.php on line 9 Call Stack: 0.0022 739320 1. {main}() test.php:0 0.0028 741512 2. file_put_contents() test.php:9
Try a simple file_put_contents('path/to/your/file', "test"); and see if it works. Also post your exact code line where you use file_put_contents. My code is fine if used properly, and also if you have permissions on the target file.
i think it was write permissions..it works but output 30. what is the 30 for? also how do I decrypt the file. Is it AES 128 encryption?
Debug your code to see what values $text and $crypttext are getting. I gave you an answer assuming you have the basic string encoding nailed.
@Is it AES 128 encryption? Read this article better en.wikipedia.org/wiki/Rijndael . It's AES 256, but the block size is always 128.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.