Wednesday, January 23, 2013

Simple method to encrypt and decrypt files in PHP

1/23/2013

Simple way to encrypt and decrypt files in php

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/



function CryptFile($InFileName,$OutFileName,$password){
//check the file if exists
if (file_exists($InFileName)){

//get file content as string
$InFile = file_get_contents($InFileName);

// get string length
$StrLen = strlen($InFile);

// get string char by char
for ($i = 0; $i < $StrLen ; $i++){
//current char
$chr = substr($InFile,$i,1);

//get password char by char
$modulus = $i % strlen($password);
$passwordchr = substr($password,$modulus, 1);

//encryption algorithm
$OutFile .= chr(ord($chr)+ord($passwordchr));
}

$OutFile = base64_encode($OutFile);

//write to a new file
if($newfile = fopen($OutFileName, "c")){
file_put_contents($OutFileName,$OutFile);
fclose($newfile);
return true;
}else{
return false;
}
}else{
return false;
}
}




function DecryptFile($InFileName,$OutFileName,$password){
//check the file if exists
if (file_exists($InFileName)){

//get file content as string
$InFile = file_get_contents($InFileName);
$InFile = base64_decode($InFile);
// get string length
$StrLen = strlen($InFile);

// get string char by char
for ($i = 0; $i < $StrLen ; $i++){
//current char
$chr = substr($InFile,$i,1);

//get password char by char
$modulus = $i % strlen($password);
$passwordchr = substr($password,$modulus, 1);

//encryption algorithm
$OutFile .= chr(ord($chr)-ord($passwordchr));
}

//write to a new file
if($newfile = fopen($OutFileName, "c")){
file_put_contents($OutFileName,$OutFile);
fclose($newfile);
return true;
}else{
return false;
}
}else{
return false;
}
}

//Example
$orginalfile = 'orginal.jpg';
$crypt = 'crypt.jpg';
$decrypt = 'decrypt.jpg';
$password = 'pass';

CryptFile($orginalfile,$crypt,$password);
DecryptFile($crypt,$decrypt,$password);

?>






helpful? Share this

The Editorial Team of 4everTutorials consists of a group of PHP Professionals.

2 comments:

Anonymous said...

Nice Script Working Fine...

Anonymous said...

Your script is nice, but the script loading time is too long when we convert video file..

It has take too long time based on file size.


Regards,

S.Perumal

 

© 2014 4everTutorials. All rights resevered.

Back To Top