Solved

Encrypt static variables

Posted on 2013-01-20
16
422 Views
Last Modified: 2013-02-14
I have a custom PHP application, and I have a few static values that work with API's and will not change.  I need to keep them in a file for testing but want to encrypt these values, so maybe need both encrypt and decrypt file.  Let me know if you have seen this before
0
Comment
Question by:Jack_son_
  • 5
  • 4
  • 3
  • +3
16 Comments
 
LVL 15

Assisted Solution

by:gplana
gplana earned 112 total points
ID: 38798931
I think this article is what you need:
http://stackoverflow.com/questions/10916284/how-to-encrypt-decrypt-data-in-php

Hope it helps. Regards
0
 
LVL 142

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 56 total points
ID: 38798952
as the file is on the web server, and only "included" as php file, so it won't arrive on the client side, why "encrypt" them?
file protection should be enough?
0
 

Author Comment

by:Jack_son_
ID: 38798956
if someone gets on the server ever and gets access to the keys, it would cause havoc, thats the main reason; so encrypting them is important.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
ID: 38799040
I think you will be OK putting the file with the keys above the WWW root.  That way, even if PHP fails and the server belches out the raw PHP code, the keys will not be available.  Encryption will not really buy you very much because the keys will have to be somewhere that they can be used with the encrypted string.  If someone gets to the encrypted string, they can probably get to the keys, too.

If you do not trust the people who run your server, that is a separate problem.  And if you're running an important application on a shared server, that is an even greater problem.  But in any case just put them in a file above the WWW root and you'll probably be OK.
0
 
LVL 15

Assisted Solution

by:gplana
gplana earned 112 total points
ID: 38799107
Ray: I mostly agree, but encripting data is an additional security policy. I think it's useful. A simple php programming error can allow a user to enter to the server...
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
ID: 38799311
Here is an example of how to encrypt/decrypt.  I always look at security and consider the compromise between safety and convenience (in other words, how can I make security suck less).  If it's bowling scores, your security levels are different when compared to medical records, financial transactions and nuclear launch codes.

You can experiment with it here:
http://laprbass.com/RAY_encrypt_decrypt.php

<?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

Footnote: Scientists at MIT and NSA spend a lifetime working on these issues.  Best to all, ~Ray
0
 

Author Comment

by:Jack_son_
ID: 38799458
Understood; I like this, so after I encrypt, to decrypt I would use this function in my code?

 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];
0
 
LVL 51

Expert Comment

by:ahoffmann
ID: 38800114
> if someone gets on the server ever and gets access ... it would cause havoc, thats the main reason; so encrypting them is important.

if someone gets to the server and can read your code, it doesn' matter if the file is encrypted or not, unless the en-/decryption **always** requieres to enter a passphrase manually
is this what you want?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
ID: 38800825
No, you cannot use that function standalone.  It is part of a class.  The entire class is required.  Of course you can store the class outside of the WWW root, bring it in, run it, recover the API keys or DB passwords, call the API and DB, then unset the variables and delete the object.  

Maybe if you can describe the information you're trying to protect and the "havoc" you're concerned about we could offer some suggestions that would make sense for your application.

@ahoffmann makes a very good point.  The encryption keys are required to reverse the encryption.  So you would need to type the encryption key into your web site every time you or anyone else loads a web page.  You could store this key somewhere, but then you have only created a modest additional step for someone intent on cracking the web site.  The attacker would simply read your code and follow the path back through the variables to locate the key.

Are you running you site on a dedicated server?
0
 

Author Comment

by:Jack_son_
ID: 38801011
Yes it is a dedicated server; idea is the application will grab these static values to run an API. I guess what I'm trying to get is how to decrypt, I'm assuming just call the class?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38801201
The correct terminology would probably be to "call a method on an object instance of the class."  If the class definition is not obvious to you, we might be best off to return to this:  Maybe if you can describe the information you're trying to protect and the "havoc" you're concerned about we could offer some suggestions that would make sense for your application. In other words, encryption is not the only thing you can consider for application security.  What API are you trying to protect?
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 166 total points
ID: 38803367
greetings Jack_son_ , , the MCRYPT encryption is not an easy thing to understand, because it gets BINARY returns (not human understandable letters)  strings, , and there are other factors to consider to use it with any good effect for security. The "KEY" in this encryption thing is a very important thing because it is the very secrete Key that actually protects the encrypt, if not a secrete there is little protection, but you seem to have no idea about it.

Not sure encrypt functions will help you, as you may not be experienced in PHP, Here's a couple for encrypt and decrypt with CBC randomization for better security -

function CBC_encrypt($Plain, $Key, $base64 = false, $MAC = false){
$sLen=strlen($Plain);
if($sLen<4){return false;}
if(!isset($Key{9})){return false;}
$Key=str_pad($Key,32,chr(8).chr(219).'nH!`>;0'.chr(244).'{b3?m$1Lf@');
if ($MAC) {$MAC = md5($Plain, true);
	echo $MAC,'<br />';
	$Plain= $MAC.$Plain;}
$chop = 15-($sLen%16);
$Plain= chr($chop).$Plain;
$ivRand = mcrypt_create_iv(16, MCRYPT_RAND);
$Plain = mcrypt_encrypt('twofish', $Key, $Plain, 'cbc', $ivRand);
$Key = strrev(substr($ivRand ,7));
$ivRand = substr($ivRand ,0,7);
$Plain = $Key.$Plain.$ivRand;
if ($base64) return str_rot13(base64_encode($Plain));
return $Plain;
}

function CBC_decrypt($Input, $Key, $base64 = false, $MAC = false){
if ($base64) $Input = base64_decode(str_rot13($Input));
$sLen=strlen($Input);
if (($sLen <32) || ($sLen % 16 != 0)) return false;
if(!isset($Key{9}))return false;
$Key=str_pad($Key,32,chr(8).chr(219).'nH!`>;0'.chr(244).'{b3?m$1Lf@');
$ivRand = substr($Input,$sLen-7);
$chop = strrev(substr($Input,0,9));
$ivRand .= $chop;
$Input = substr($Input,9,-7);
$sLen -=17;
$Input = mcrypt_decrypt('twofish',$Key,$Input,'cbc', $ivRand);
$chop = ord($Input[0]);
if ($chop > 15) return false;
if ($MAC) {
	$MAC = substr($Input,1,16);
	echo $MAC,'<br />';
	$sLen -=16;
	$Input = substr($Input,17,$sLen-$chop);
	if ($MAC == md5($Input, true)) echo 'EQUAL<br />'; else echo 'NOT EQUAL<br />';
	return $Input;
	}
if($chop ==0)$Input=substr($Input,1); else $Input=substr($Input,1,$sLen-$chop);
return $Input;
}

Open in new window


 to encrypt a string
$keyE = 'v^5Uk!m:[+cDn}5!sA'; // use Longer strings with mixed random looking characters
$plain = $class1::static1;
$encrypted = CBC_encrypt($plain, $keyE);
file_put_contents('encrypt.enc', $encrypted);

Open in new window



to decrypt a string
$keyD = 'v^5Uk!m:[+cDn}5!sA'; // IMPORTANT KEY must match exactly as encrypt
$input = file_get_contents('encrypt.enc');
$decrypted = CBC_decrypt($input, $keyD);

Open in new window


to keep it simple i did not include ant error checking, but these functions will not work with Plain strings less than four length and will not work with a KEY less than 10 in length.
ask questions if you need more info
0
 

Author Comment

by:Jack_son_
ID: 38803508
Okay, thanks.  How can I allow it to support longer strings?  Also, once I get the string encrypted, does it create a decryption key or how do I get it decrypted.  The idea is I can encrypt these values and save them securely, then I need the function to decrypt or provide a decryption key?
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 166 total points
ID: 38803694
sorry Jack_son_  , but I do not understand Anything you say in your last post ? ?
you ask = "How can I allow it to support longer strings?"
I have not seen any code presented here that does not allow very long strings, so there is no problem with that for whats here?, but you really do not say what errors you get in the code you tried, and show us the code you tried.

you say = "once I get the string encrypted, does it create a decryption key"
short answer is NO, , it does not,
 the KEY is the developers string to tell the encyptor function-method how to mix-up and scramble the plain text, so that the SAME IDENTICAL key string used by the code writer (you) will succeed as the KEY for the decryptor function-method.
You also say = " I can encrypt these values and save them securely, then I need the function to decrypt or provide a decryption key?"
Not sure what you are asking, but you can encrypt and decrypt strings,  BUT your "function to provide a decryption key" is not a part of the steps you take to do this sort of thing. . . As far as my code in post ID: 38803367 it shows the steps you take in code to decrypt - Please Notice the name of the function used = CBC_decrypt( ), it states that it is the decrypt function, also notice that the KEY as $keyD, is typed in on keyboard by the coder as a string value, not generated or recovered by a function.

$keyD = 'v^5Uk!m:[+cDn}5!sA'; // IMPORTANT KEY must match exactly as encrypt KEY
$input = file_get_contents('encrypt.enc');
$decrypted = CBC_decrypt($input, $keyD);

Open in new window


also my CBC_encrypt(  )  function can take LONG length strings for the $plain.
If you have trouble with this not so complex idea in encryption, you may want to take another code method for this set-up.
You still have not told us what the reasons you doubt your security to help protect it, and some of the code used by you so we can see a way to help you.
Giving you Class and or function code does not seem to be something you can use.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38803787
Pronouns are the enemy of human communication.  Example: How can I allow it to support longer strings?  By it do you mean the key, the source data, the EOT or what, exactly?

Encryption as illustrated in my example depends on the key and the EOT string.  These must be known to both sides of the process.

And I still think you may be overthinking this whole process.  Please tell us about the information you're trying to protect.  What is it in information terms -- strings?  how long? etc.  What is its value in economic terms?  Would a breach cost thousands of dollars?  thousands of lives?

Armed with a little more information we can possibly offer common sense solutions and references that might help you make the best decision.

Thanks, ~Ray
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 166 total points
ID: 38807187
@ Jack_son_  , ,  you said = "I need to keep them in a file", , can you show us the code you use now to write your string (or strings) to file, maybe something using the PHP function fopen( ), similar to -
$saveStr  =  myClass::$my_static;
$handle = fopen("save1.txt", "w");
if (fwrite($handle, $saveStr) === FALSE) {
        echo "Cannot write to file save1.txt";
        exit;
    }

    echo "Success, wrote static to file save1.txt";

    fclose($handle);

Open in new window


or using the  file_put_contents( ) function

$saveStr  =  myClass::$my_static;
if (file_put_contents("save1.txt", $saveStr) )
    echo "Success, wrote static to file save1.txt";


And show code you use to read the file and get the String.
if you have not done any string save to file and read from file code, we could help you with that first? ?

with these code writes of yours, we could help with a simple encrypt - decrypt code for you, that you should be able to copy and paste into PHP script and see if it works for you.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article explains in simple steps how to renew expiring Exchange Server Internal Transport Certificate.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

758 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

20 Experts available now in Live!

Get 1:1 Help Now