Solved

PHP / Linux encrypt file

Posted on 2012-12-28
9
678 Views
Last Modified: 2013-01-13
How do I encrypt a file for a PHP app; it is the file that holds any relevant passwords for the application?

Thanks
0
Comment
Question by:Jack_son_
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 53

Assisted Solution

by:COBOLdinosaur
COBOLdinosaur earned 72 total points
ID: 38727300
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 143 total points
ID: 38727308
Here is one way to encrypt and decrypt.  Usage example is at the bottom of the class.
<?php // RAY_encrypt_decrypt.php
error_reporting(E_ALL);

// MAN PAGE: http://php.net/manual/en/ref.mcrypt.php

class Encryption
{
    protected $key;
    protected $eot;
    protected $ivs;
    protected $iv;

    public function __construct($key='quay', $eot='___EOT')
    {
        // SET KEY, DELIMITER, INITIALIZATION VECTOR - MUST BE KNOWN TO BOTH PARTS OF THE ALGORITHM
        $this->key = $key;
        $this->eot = $eot;
        $this->ivs = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $this->iv  = mcrypt_create_iv($this->ivs);
    }

    public function encrypt($text)
    {
        // APPEND END OF TEXT DELIMITER
        $text .= $this->eot;

        // ENCRYPT THE DATA
        $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv);

        // MAKE IT base64() STRING SAFE FOR STORAGE AND TRANSMISSION
        return base64_encode($data);
    }

    public function decrypt($text)
    {
        // DECODE THE DATA INTO THE BINARY ENCRYPTED STRING
        $text = base64_decode($text);

        // DECRYPT THE STRING
        $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv);

        // REMOVE END OF TEXT DELIMITER
        $data = explode($this->eot, $data);
        return $data[0];
    }
}

// INSTANTIATE THE CLASS
$c = new Encryption();

// INITIALIZE VARS FOR LATER USE IN THE HTML FORM
$encoded = '';
$decoded = '';

// IF ANYTHING WAS POSTED SHOW THE DATA
if (!empty($_POST["clearstring"]))
{
    $encoded = $c->encrypt($_POST["clearstring"]);
    echo "<br/>{$_POST["clearstring"]} YIELDS ENCODED ";
    var_dump($encoded);
}

if (!empty($_POST["cryptstring"]))
{
    $decoded = $c->decrypt($_POST["cryptstring"]);
    echo "<br/>{$_POST["cryptstring"]} YIELDS DECODED ";
    var_dump($decoded);
}

$form = <<<FORM
<form method="post">
<input name="clearstring" value="$decoded" />
<input type="submit" value="ENCRYPT" />
<br/>
<input name="cryptstring" value="$encoded" />
<input type="submit" value="DECRYPT" />
</form>
FORM;

echo $form;

Open in new window

0
 
LVL 9

Assisted Solution

by:abolinhas
abolinhas earned 142 total points
ID: 38727450
Hi,

You want encrypt your php file (your code) or just the form data ?

If you want encrypt your code you need something like ZEND GUARD.
http://www.zend.com/en/products/guard/

For the second case, I recomend  a good SSL certificate.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 143 total points
ID: 38727511
@abolinhas: Good point - we're not exactly sure what we're encrypting!

There is also this: http://www.ioncube.com/
0
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

 
LVL 9

Assisted Solution

by:abolinhas
abolinhas earned 142 total points
ID: 38727535
ioncube is a good encoder to.

whichever the encoder that you choose you need to install / enable the same extension on your php.ini, eg:
"Zend Optimizer 3.3" (for PHP 5.1 and 5.2) or "Zend Guard Loader" (for PHP 5.3) or "ionCube" (for PHP 5.3 and 5.4)
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 143 total points
ID: 38728232
greetings   Jack_son,  Encryption is not a simple thing to setup and be "Secure", since you say -"the file that holds any relevant passwords" is what needs to be encrypted, I would recommend a randomized variable encryption as the CBC mode offers, due to the extra safety for passwords.

below is some code for PHP Class that does a MAC (message authentication code) using the CBC mode for randomize, and Checks the decrypt for authentication to ensure it's legit (correct).

class encError{public $Number=0,$Message='No Errors',$fail=false;
public function set($eNum=0,$eMes=''){if($eNum<1){$this->fail=false;$this->Message='No Errors';return;}else$this->fail=true;
$this->Number=$eNum;if($eNum>99)$this->Message='ERROR in Decrypt function: '.$eMes;else$this->Message='ERROR in Encrypt function: '.$eMes;}
}

class macCBC {

function __construct($base64 = false){
$this->base64=$base64;
$this->Error=new encError;
$this->algor='twofish';// 'serpent' 'rijndael-128' 'saferplus' 'loki97'
}

public function encrypt($Plain, $Key){
if((!is_string($Key))||(!isset($Key{15}))){$this->Error->set(10,'Key String length less than SIXTEEN');return false;}
$sLen=strlen($Plain);
if($sLen<4){$this->Error->set(20,'Plain String length less than FOUR');return false;}
if($this->Error->fail)$this->Error->set();
$Key=str_pad($Key,32,chr(8).chr(219).'nH!`'.chr(244).'>;0');
$ivRand=mcrypt_create_iv(12,MCRYPT_RAND);
$chop=substr($ivRand ,6,4);
$check=hash_hmac('crc32b',$Plain,$chop,true);
$chop=15-($sLen%16);
$Plain=chr($chop).$Plain;
$check^=$ivRand{10}.$ivRand{3}.$ivRand{5}.$ivRand{9};
$ivRand.=$check;
$chop=$ivRand{13};
$ivRand{13}=$ivRand{2};
$ivRand{2}=$chop;
$check=str_split($Key,16);
$check[0]^=$ivRand;
$check[1]^=$ivRand;
$Key=$check[1].$check[0];
$Plain=mcrypt_encrypt($this->algor, $Key, $Plain, 'cbc', $ivRand);
if($Plain==''){$this->Error->set(30,'MCRYPT function FAILED');return false;}
$Key=strrev(substr($ivRand,7));
$ivRand=substr($ivRand ,0,7);
$Plain=$Key.$Plain.$ivRand;
if($this->base64){$Plain=base64_encode($Plain);$Plain=str_rot13($Plain);return $Plain;}
return $Plain;
}

public function decrypt($Input, $Key){
if((!is_string($Key))||(!isset($Key{15}))){$this->Error->set(100,'Key String length less than SIXTEEN');return false;}
$sLen=strlen($Input);
if($this->base64){if(($sLen<44)||($sLen%4!=0)){$this->Error->set(300,'Incorrect Base64 length of Input string');return false;}
if(preg_match('/[^a-zA-Z0-9\+\=\/]/',$Input)!=0){$this->Error->set(301,'Incorrect Base64 characters in Input string');return false;}
$Input=str_rot13($Input);$Input=base64_decode($Input);$sLen=strlen($Input);}
if(($sLen<32)||($sLen%16!=0)){$this->Error->set(200,'Input string length is NOT Block Size');return false;}
if($this->Error->fail)$this->Error->set();
$Key=str_pad($Key,32,chr(8).chr(219).'nH!`'.chr(244).'>;0');
$ivRand=substr($Input,$sLen-7);
$chop=strrev(substr($Input,0,9));
$ivRand.=$chop;
$Input=substr($Input,9,-7);
$sLen-=17;
$check=str_split($Key,16);
$check[0]^=$ivRand;
$check[1]^=$ivRand;
$Key=$check[1].$check[0];
$Input=mcrypt_decrypt($this->algor,$Key,$Input,'cbc', $ivRand);
if($Input==''){$this->Error->set(500,'MCRYPT function FAILED');return false;}
$chop=ord($Input[0]);
if($chop>15){$this->Error->set(400,'FAILED to Decrypt correctly; INVALID Output');return false;}
if($chop==0)$Input=substr($Input,1);else $Input=substr($Input,1,$sLen-$chop);
$chop=$ivRand{13};
$ivRand{13}=$ivRand{2};
$ivRand{2}=$chop;
$check=substr($ivRand,12);
$check^=$ivRand{10}.$ivRand{3}.$ivRand{5}.$ivRand{9};
$chop=substr($ivRand ,6,4);
$Key=hash_hmac('crc32b',$Input,$chop,true);
if($check!=$Key){$this->Error->set(400,'FAILED to Decrypt correctly; INVALID MAC');return false;}
return $Input;
}

public function RandKeyText($length=32, $less=true){$out='$key = ';$rand=0;$apos=false;
for($i=0;$i<$length;++$i){if(($less)&&($i&1))$rand=mt_rand(32,127);else$rand=mt_rand(0,255);
	if (($rand>31)&($rand<127)){if(!$apos)$out .='\'';$apos=true;if(($rand==39)|($rand==92))$out .='\\';$out .=chr($rand);}
	else{if($apos)$out .='\'.';$apos=false;$out .='chr('.$rand.').';}}
if($apos)$out .= '\';';else $out[strlen($out)-1]=';';
return htmlspecialchars($out);}

} // end of class macCBC

Open in new window


This does NOT allow a key length of less than 16, and will error out if key is 9 or less, you should always use a KEY string of 32 length (bytes) for good security.


 you asked to Encrypt a file, here's the code -
$maC = new macCBC();
$key = 'kO*b4Wc+,Ov!dR6$."pIjHtgP3!`B;}d';// use random 32 length key
$plain = file_get_contents('ord2.jpg');
if($encrypted = $maC->encrypt($plain, $key)) {
	$fileName = 'my.data';// can be ANY name and extention
	file_put_contents($fileName, $encrypted);
	echo 'New File made as ',$fileName,' with a size of ',strlen($encrypted),' Bytes.';
	} else echo $maC->Error->Number,'-',$maC->Error->Message,'<hr /><br />';

Open in new window


ask questions if you need more info
0
 

Author Comment

by:Jack_son_
ID: 38729004
Great, thanks.  So the information that I am encrypting is only the passwords the application uses.   For the code you have, do I call this class to encrypt the passwords or how do I set this up?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38729093
Are you sure you need to encrypt application passwords?  Please tell us a little more about the application, the kind of passwords, etc.  It might not be necessary at all!
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 143 total points
ID: 38729540
@: Jack_son_
Sorry, you have given so LITTLE necessary information about what you are doing and how you need to do it, , I do not know how to respond to your last comment here as ID: 38729004;

there have been two different two different CLASS codes here, and you do not say which CLASS you refer to ? ?

In your original question you ask about encrypting a "File" +++ and then in your last comment ID: 38729004;  you ask about "encrypt the passwords"

In my class  macCBC( )   you can encrypt or decrypt "Anything" you can get into PHP string variable, and for almost any encrypt Class or the MCRYPT functions, you have a string variable to encrypt (decrypt).  But you do not say anything about what you need to do with the password (or maybe more than one password bundled together, somehow) once you have them encrypted?

this is not that complex to have a string and then encrypt it
$plain = 'password';
$key = chr(251).chr(197).chr(3).'!mo{8'.chr(202).'D)l@]'.chr(237).'k0'.chr(12).'C5('.chr(17).'%[Bi3'.chr(28).'dH6'.chr(130);
$maC = new macCBC();
if($encrypted = $maC->encrypt($plain, $key)) {
// $encrypted has the hidden data of the $plain, which you can store somewhere (database or file or cloud)
	echo 'encrypt successful  with a size of ',strlen($encrypted),' Bytes.';
	} else echo $maC->Error->Number,'-',$maC->Error->Message,'<hr /><br />';

Open in new window


as I said, this security "for the web application" has more considerations than just encryption.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been asked to discuss some of the UX activities that I'm using with my team. Here I will share some details about how we approach UX projects.
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now