473,406 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Encryption & Decryption script

I get bored last night and wrote a script that uses xor for encrypt-
decrypt, however it woks fine under linux 2.6.25, text and documents
are ok, but fails on compressed files *.jpg, *.pdf , etc . I didn't
test script on windows.

Here is the code, please send me your views.

<?php

/* Mother Eye Chipper with PHP :), Licence:GPL,
Author: Barış ÇUHADAR
Prepared to use in Console,
usage: "for encryption: php chipper.php -e <key<file>"
"for decryption: php chipper.php -d <key<file>" */

echo "A Basic Encryption & Decryption Program\n";
if(isset($argv[1]) && isset($argv[2]) && is_file($argv[3]) && $argv[3]!
=$_SERVER['PHP_SELF'])
{
$process = $argv[1];
$key = $argv[2];
$file = $argv[3];

if($process == "-e")
{
encrypt_file($file,$key);
}
else if($process == "-d")
{
decrypt_file($file,$key);
}
}
else
{
if($argc < 4)
echo "missing parameters\n \tdefault usage: php chipper.php [-e/-d]
<key<filename>\n";
else if(!is_file($argv[3]))
echo "file " . $argv[3] . " can not be found or is not a file\n";
else if($argv[3]==$_SERVER['PHP_SELF'])
echo "trying to encrypt own file\n";
else echo "unfortunately program is fubar\n";
}

/************************************************** **/
/* encryption begins */
function encrypt_file($file,$key)
{
$k = 0;
$fp_r = fopen($file,"rb");
$cont = fread($fp_r,12);
if($cont == "encrypted_so")
{
fclose($fp_r);
die("file is encrypted! can not be encrypted again!
\n");
}
while(!feof($fp_r))
{
$foo = fread($fp_r,65536);
for($i = 0; $i < strlen($foo); $i++)
{
$r[$i] = $foo[$i] ^ $key[$k];

if($k==sizeof($key))
$k = 0;
$k++;
}
$fp_w = fopen($file . "_temp","a");
/* encrypted content is being written on file*/
fwrite($fp_w,"encrypted_so");
for($i = 0; $i < sizeof($r); $i++)
fwrite($fp_w,$r[$i]);
fclose($fp_w);
$foo=null;
$k=0;
}
fclose($fp_r);
unlink($file);
rename($file . "_temp",$file);
echo "Encryption made successfully!\n";
}
/************************************************** **/
/* decryption */
function decrypt_file($file,$key)
{
$k = 0;
$fp_r = fopen($file,"rb");
$cont = fread($fp_r,12);
if($cont != "encrypted_so")
{
fclose($fp_r);
die("file is not encrypted! so can not
be decrypted..\n");
}
while(!feof($fp_r))
{
$r = fread($fp_r,65536);
for($i = 0; $i < strlen($r); $i++)
{
$foo[$i] = $r[$i] ^ $key[$k];

if($k==sizeof($key))
$k =0;
$k++;
}
/* decrypted content is being written on file */
$fp_w = fopen($file . "_temp","a");
for($i = 0; $i < sizeof($foo); $i++)
fwrite($fp_w,$foo[$i]);
fclose($fp_w);
}
fclose($fp_r);
unlink($file);
rename($file . "_temp",$file);
echo "Decryption made successfully!\n";
}

?>
Sep 30 '08 #1
9 4805
I get bored last night and wrote a script that uses xor for encrypt-
decrypt, however it woks fine under linux 2.6.25, text and documents
are ok, but fails on compressed files *.jpg, *.pdf , etc . I didn't
test script on windows.
I did not look at the code, but xor on PHP is quite counter-intuitive.
The most significant bit is seen as a sign bit and is treated special.
Furthermore, the size of an integer is not determined. I ended up
creating my own fixed size integer classes when I had to implement a
decryption algorithm.

Best regards,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Sep 30 '08 #2
^ (bitwise operator) is for ascii values, won't work on binary.
need to convert from binary to at least decimal or maybe hex before
xor. You'll have to break it up into 8 bits as well to get a valid
ascii character.

Sep 30 '08 #3
could try:

while(!feof($fp_r)) {

$r = fread($fp_r,65536);

if (is_binary($r)) {
$binArray = split('[0-1]{8}',$r); //or use \d{8}
$r = '';
foreach ($binArray as $value) {
$r .= bindec($value);
}
//Could use array_walk as well

for($i = 0; $i < strlen($r); $i++) {
$foo[$i] = $r[$i] ^ $key[$k];

if($k==sizeof($key))
$k =0;
$k++;
} .....
Sep 30 '08 #4
On Sep 30, 4:40*pm, The Hajj <hajji.hims...@gmail.comwrote:
^ (bitwise operator) is for ascii values, won't work on binary.
need to convert from binary to at least decimal or maybe hex before
xor. You'll have to break it up into 8 bits as well to get a valid
ascii character.
I cosidered that before but when read file as whole there is no
problem, using fread($fp,filesize($file) or file_get_contents($file).
However fread($fp,65536) or else makes the case, breaks the bit
block ;). For now i removed "encrypted_so" part...

<?php
define("READ_SIZE",1000000);
/* Mother Eye Chipper with PHP, Licence:GPL,
Author: Barış ÇUHADAR
Prepared to use in Console,
usage: "for encryption: php chipper.php -e <key<file>"
"for decryption: php chipper.php -d <key<file>" */
echo "A Basic Encryption & Decryption Program\n";
if(isset($argv[1]) && isset($argv[2]) && is_file($argv[3]) && $argv[3]!
=$_SERVER['PHP_SELF'])
{
$process = $argv[1];
$key = $argv[2];
$file = $argv[3];

if($process == "-e")
{
encrypt_file($file,$key);
}
else if($process == "-d")
{
decrypt_file($file,$key);
}
}
else
{
if($argc < 4)
echo "missing parameters\n \tdefault usage: php chipper.php [-e/-d]
<key<filename>\n";
else if(!is_file($argv[3]))
echo "file " . $argv[3] . " can not be found or is not a file\n";
else if($argv[3]==$_SERVER['PHP_SELF'])
echo "trying to encrypt own file\n";
else echo "unfortunately program is fubar\n";
}

/************************************************** **/
/* encryption begins */
function encrypt_file($file,$key)
{
$flag = false;
$k = 0;
$fp_r = fopen($file,"rb");
while(!feof($fp_r))
{
$foo = fread($fp_r,READ_SIZE);
for($i = 0; $i < strlen($foo); $i++)
{
$r[$i] = $foo[$i] ^ $key[$k];

if($k==sizeof($key))
$k = 0;
$k++;
}
$fp_w = fopen($file . "_temp","a");
/* encrypted content is being written on file*/
for($i = 0; $i < sizeof($r); $i++)
fwrite($fp_w,$r[$i]);
fclose($fp_w);
$foo=null;
$k=0;
}
fclose($fp_r);
unlink($file);
rename($file . "_temp",$file);
echo "Encryption made successfully!\n";
}
/************************************************** **/
/* decryption */
function decrypt_file($file,$key)
{
$k = 0;
$fp_r = fopen($file,"rb");
while(!feof($fp_r))
{
$r = fread($fp_r,READ_SIZE);
for($i = 0; $i < strlen($r); $i++)
{
$foo[$i] = $r[$i] ^ $key[$k];

if($k==sizeof($key))
$k =0;
$k++;
}
/* decrypted content is being written on file */
$fp_w = fopen($file . "_temp","a");
for($i = 0; $i < sizeof($foo); $i++)
fwrite($fp_w,$foo[$i]);
fclose($fp_w);
}
fclose($fp_r);
unlink($file);
rename($file . "_temp",$file);
echo "Decryption made successfully!\n";
}

?>
Sep 30 '08 #5
..oO(The Hajj)
>^ (bitwise operator) is for ascii values, won't work on binary.
Huh? Where did you get that from? What's the difference between an ASCII
byte and a binary byte?
>need to convert from binary to at least decimal
If you read a byte from somewhere it _is_ decimal, it's always a numeric
value between 0..255. Of course you can interpret it in different ways.

Micha
Sep 30 '08 #6
..oO(Betikci Boris)
>I get bored last night and wrote a script that uses xor for encrypt-
decrypt, however it woks fine under linux 2.6.25, text and documents
are ok, but fails on compressed files *.jpg, *.pdf , etc . I didn't
test script on windows.

Here is the code, please send me your views.
[...]
There are some logical flaws in the code and I'm wondering if it worked
at all:

* The encrypt_file() function reads the first 12 bytes to check if the
file is already encrypted, but then doesn't jump back to the beginning
of the file when the encryption process starts.

* With bigger files you'll end up with the string 'encrypted_so' being
scattered across the entire file, because your encryption loop may open
and close the target file multiple times and will write that string
before every chunk of 64K.

* These lines

if ($k == sizeof($key))
$k = 0;
$k++;

will cause E_NOTICE errors after the first run of the loop. From there
on the first char of the key will be ignored. Additionally sizeof() is
an alias for count(), which only works on arrays, not on strings. So it
should be something like

$k++;
if ($k == strlen($key)) {
$k = 0;
}

instead.

But IMHO the biggest problem is that you use strlen() on binary data.
This function should not be considered binary-safe! If the Multibyte
extension is enabled, strlen() might be overloaded with mb_strlen().
This means that it tries to work on chars, not on bytes anymore. If you
compare the output of strlen() and filesize() of a small binary file,
you'll most likely get different results. To solve this issue, you could
use a little helper function like this to get the real binary size:

function strSize($string) {
return extension_loaded('mbstring')
? mb_strlen($string, '8bit')
: strlen($string);
}

You should also consider to move the encryption/decryption part to a
seperate function, because the algorithm is the same. With some little
improvements it may look like this:

function codec($fp_r, $fp_w, $key) {
$keySize = strSize($key);
$k = 0;
while (!feof($fp_r)) {
$data = fread($fp_r, 65536);
$result = '';
for ($i = 0, $c = strSize($data); $i < $c; $i++) {
$result .= $data[$i] ^ $key[$k];
$k++;
if ($k == $keySize) {
$k = 0;
}
}
fwrite($fp_w, $result);
}
}

Given these two little helpers, your main functions may now look like
this (I've restructured the code a bit to make it more readable for me):

function encrypt_file($file, $key) {
$fp_r = fopen($file, 'rb');
if (fread($fp_r, 12) == 'encrypted_so') {
fclose($fp_r);
die("file is encrypted! can not be encrypted again!\n");
}
fseek($fp_r, 0);
$fp_w = fopen("{$file}_temp", 'wb');
fwrite($fp_w, 'encrypted_so');
codec($fp_r, $fp_w, $key);
fclose($fp_r);
fclose($fp_w);
unlink($file);
rename("{$file}_temp", $file);
echo "Encryption made successfully!\n";
}

function decrypt_file($file, $key) {
$fp_r = fopen($file, 'rb');
if (fread($fp_r, 12) != 'encrypted_so') {
fclose($fp_r);
die("file is not encrypted! so can not be decrypted..\n");
}
$fp_w = fopen("{$file}_temp", 'wb');
codec($fp_r, $fp_w, $key);
fclose($fp_r);
fclose($fp_w);
unlink($file);
rename("{$file}_temp", $file);
echo "Decryption made successfully!\n";
}

Tested on a small text file, a GIF and an MP3. All worked well.

HTH
Micha
Sep 30 '08 #7
..oO(Willem Bogaerts)
>I get bored last night and wrote a script that uses xor for encrypt-
decrypt, however it woks fine under linux 2.6.25, text and documents
are ok, but fails on compressed files *.jpg, *.pdf , etc . I didn't
test script on windows.

I did not look at the code, but xor on PHP is quite counter-intuitive.
The most significant bit is seen as a sign bit and is treated special.
Can you elaborate on that or give an example?

<?php
$foo = 129; // 10000001b
$bar = 66; // 01000010b
$huh = 200; // 11001000b
var_dump(decbin($foo ^ $bar)); // 11000011b
var_dump(decbin($foo ^ $huh)); // 01001001b
var_dump(decbin($bar ^ $huh)); // 10001010b
var_dump(decbin($foo ^ $bar ^ $huh)); // 00001011b
?>

All as expected.

Micha
Sep 30 '08 #8
On Sep 30, 6:58*pm, Michael Fesser <neti...@gmx.dewrote:
.oO(Betikci Boris)
I get bored last night and wrote a script that uses xor for encrypt-
decrypt, however it woks fine under linux 2.6.25, text and documents
are ok, but fails on compressed files *.jpg, *.pdf , etc . I didn't
test script on windows.
Here is the code, please send me your views.
[...]

There are some logical flaws in the code and I'm wondering if it worked
at all:

* The encrypt_file() function reads the first 12 bytes to check if the
file is already encrypted, but then doesn't jump back to the beginning
of the file when the encryption process starts.

* With bigger files you'll end up with the string 'encrypted_so' being
scattered across the entire file, because your encryption loop may open
and close the target file multiple times and will write that string
before every chunk of 64K.

* These lines

* if ($k == sizeof($key))
* * $k = 0;
* $k++;

will cause E_NOTICE errors after the first run of the loop. From there
on the first char of the key will be ignored. Additionally sizeof() is
an alias for count(), which only works on arrays, not on strings. So it
should be something like

* $k++;
* if ($k == strlen($key)) {
* * $k = 0;
* }

instead.

But IMHO the biggest problem is that you use strlen() on binary data.
This function should not be considered binary-safe! If the Multibyte
extension is enabled, strlen() might be overloaded with mb_strlen().
This means that it tries to work on chars, not on bytes anymore. If you
compare the output of strlen() and filesize() of a small binary file,
you'll most likely get different results. To solve this issue, you could
use a little helper function like this to get the real binary size:

* function strSize($string) {
* * return extension_loaded('mbstring')
* * * ? mb_strlen($string, '8bit')
* * * : strlen($string);
* }

You should also consider to move the encryption/decryption part to a
seperate function, because the algorithm is the same. With some little
improvements it may look like this:

* function codec($fp_r, $fp_w, $key) {
* * $keySize = strSize($key);
* * $k = 0;
* * while (!feof($fp_r)) {
* * * $data = fread($fp_r, 65536);
* * * $result = '';
* * * for ($i = 0, $c = strSize($data); $i < $c; $i++) {
* * * * $result .= $data[$i] ^ $key[$k];
* * * * $k++;
* * * * if ($k == $keySize) {
* * * * * $k = 0;
* * * * }
* * * }
* * * fwrite($fp_w, $result);
* * }
* }

Given these two little helpers, your main functions may now look like
this (I've restructured the code a bit to make it more readable for me):

* function encrypt_file($file, $key) {
* * $fp_r = fopen($file, 'rb');
* * if (fread($fp_r, 12) == 'encrypted_so') {
* * * fclose($fp_r);
* * * die("file is encrypted! can not be encrypted again!\n");
* * }
* * fseek($fp_r, 0);
* * $fp_w = fopen("{$file}_temp", 'wb');
* * fwrite($fp_w, 'encrypted_so');
* * codec($fp_r, $fp_w, $key);
* * fclose($fp_r);
* * fclose($fp_w);
* * unlink($file);
* * rename("{$file}_temp", $file);
* * echo "Encryption made successfully!\n";
* }

* function decrypt_file($file, $key) {
* * $fp_r = fopen($file, 'rb');
* * if (fread($fp_r, 12) != 'encrypted_so') {
* * * fclose($fp_r);
* * * die("file is not encrypted! so can not be decrypted..\n");
* * }
* * $fp_w = fopen("{$file}_temp", 'wb');
* * codec($fp_r, $fp_w, $key);
* * fclose($fp_r);
* * fclose($fp_w);
* * unlink($file);
* * rename("{$file}_temp", $file);
* * echo "Decryption made successfully!\n";
* }

Tested on a small text file, a GIF and an MP3. All worked well.

HTH
Micha
Thank you Micha! which i forgotten was fseek($fp_r,0);

Additionally, i did't understand difference between,
$k++;
if ($k == strlen($key)) {
$k = 0;
}
and

if ($k == strlen($key)) {
$k = 0;
}
$k++;

Plus =)
$flag = true;
//...
if($flag)
{
fwrite($fp_w,"encrypted_so");
$flag = false;
}

is needed in my code, but you clearified the code very well, thanks
again ;)
Sep 30 '08 #9
..oO(Betikci Boris)
>[...]
is needed in my code, but you clearified the code very well, thanks
again ;)
You're welcome.

Micha
Sep 30 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Ravi | last post by:
H I have a requirement where i need to encrypt the data using 3DES in C# and pass on the data to the Application server where i need to decrypt the data. The application server is a Unix Box...
1
by: Stephanie Yao via .NET 247 | last post by:
Hi, I've got some problem on encryption and decryption,here is my code: public string Encrypt(string eptData) { MemoryStream ms = new MemoryStream(); transformer.IV = initVec;...
2
by: sushant.bhatia | last post by:
Hi All. I'm using the NCrypto dll for RSA Encryption/Decryption (http://sourceforge.net/projects/ncrypto/). My encryption code in .Net is pretty simple. The dataToEncrypt length is 1024. The...
20
by: vermarajeev | last post by:
Hi guys, I have some text files. I need to encrypt the files and then decrypt it again. This is my first experience in encryption and decryption. I want some suggestions about how this can be...
8
by: manmit.walia | last post by:
Hello Everyone, Long time ago, I posted a small problem I had about converting a VB6 program to C#. Well with the help with everyone I got it converted. But I overlooked something and don't...
0
by: johnlim20088 | last post by:
Hi, Can someone tell me who to encrypt data using standard AES algorithm with 128 bit key in NET? Also same go for Decryption. We will have a key file for above encryption and decryption is...
3
by: mathewgk80 | last post by:
Hi all, I would like to know how can i encrypt and decrypt password using asp.net and c#.net... I would like to get some source code to do encryption and decryption.... Regards, Mathew
1
by: silpa | last post by:
Apart from the encryption and decryption methods which uses different algorithms given in different sites on Internet,I want to encrypt and decrypt data in a different manner. I will define a...
5
by: Netwatcher | last post by:
well, i started messing around with dictionaries, yet, most of the pages i found about them always talk about getting only one word out of it and turning it vice versa, i've been playing with that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.