?
Solved

Communicate Securely in PHP

Posted on 2009-12-16
22
Medium Priority
?
513 Views
Last Modified: 2012-05-08
Dear experts,

I am wondering about how can I send and get data from my PHP scripts securely, I have two PHP files one in my personal server and the other on different server (customer server), I want to send and received data from my server one to customer server one that do a job which could print "test" on web page.

How can I make sure that I am the only one who could make the requests to the PHP file in customer server, and how can I send and received the data securely (encrypted) which I am the only one who can decrypt the data even if the customer open the PHP file in his server then he won't be able to decrypt any data?

Are there any suggestions to do these jobs securely ? will be grateful for your answers.

Thanks in advance.
Regards.
0
Comment
Question by:G_API
  • 6
  • 6
  • 4
  • +3
22 Comments
 
LVL 35

Assisted Solution

by:gr8gonzo
gr8gonzo earned 200 total points
ID: 26067138
Your best bet for sending something securely is to use HTTPS / SSL. Most web servers have the capability to serve a PHP web page using HTTPS. In your case, the customer server would need to have HTTPS set up. You do this by finding out what domain you want to secure, and then getting an SSL certificate for it, and then installing that certificate onto the web server. It's not something for beginners to do, so if you're not sure about how to do these things, you may want to ask the customer's network admin to do it. Chances are they already have HTTPS set up.

Once the customer has HTTPS, all YOUR server needs to do is use PHP's cURL library to send HTTPS requests to the customer's server. All the encryption/decryption is done all in the background while the data is being transmitted, so you don't have to worry about doing any special encryption/decryption code in your PHP script.

Now, if you want to be the only one who can connect to the customer server via HTTPS, then that's a separate situation.  Usually, the best way to do this is to simply have the script on the customer's server check for a special password or something in the URL. If the passphrase doesn't exist in the URL, then the script simply aborts. So when YOUR server's script starts to connect to the customer's server, you simply include the password in the URL. Since it's all encrypted via HTTPS, it's safe to do.


have an SSL certificate for the domain
0
 
LVL 17

Assisted Solution

by:CSecurity
CSecurity earned 200 total points
ID: 26067155
Simple. Create an RSA key pair. Store private key in other server and keep public key in other side. When you are sending something to server, encrypt it with public key, other side will decrypt it with private key. When other server want to return or send some data to you, it will encrypt data with private key and you can decrypt data with public key. Until no body finds your keys, you can be 100% assured, no anyone can decrypt your data. If you choose a 1024bit RSA key, with nowadays hardware, you can make sure nobody is decrypting or using data except you and other side's server.
0
 

Author Comment

by:G_API
ID: 26067195
Hi, thanks for your suggestion about HTTPS, as you said, its best and easy way to do as I have read complex solutions before.

About the second part, its good to check for a password or something but in this way, the customer able to open and read the functions on the PHP file in his server and then he could send requests to the file instead of me? do you have other solutions ?
Regards.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 35

Expert Comment

by:gr8gonzo
ID: 26067259
I'm not sure what you meant by the last paragraph. What do you mean about the customer able to open and read functions in the PHP file?

@CSecurity - 100% assured? :)
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1200 total points
ID: 26067291
This is a great question and I will write a teaching example of how to do this, but it will take me some time to get it working well enough to post it here.  If you're patient you will be rewarded.  My model will be the PayPal Instant Payment Notification.  It is an amazingly simple handshake that seems to be very secure.

Here is how it works.  All communications are over HTTPS.

You post your data to the foreign server through a known URL
The foreign server posts the same data back to you through a known URL
You respond "VERIFIED" if the data matches.
If the foreign server gets VERIFIED from your known URL, the data source is confirmed, as well as the content of the message.
0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1200 total points
ID: 26067338
The second part of your question, "I am the only one who can decrypt the data..." is just a matter of selecting an encryption mechanism that works both ways.  That is actually the easier part of this question!

At its simplest, you could have a predefined vocabulary like this example.
<?php // RAY_encrypt.php
 
echo "<pre>";
// SHOW SOME SAMPLE PASSWORDS AND THEIR MD5 CODES
function show_pwords ($pw) {
	echo "<br />$pw = ";
	echo md5($pw);
	echo "\n";
}
 
show_pwords('Cat');
show_pwords('Dog');
show_pwords('dog');
 
 
//  FORM TO RECEIVE INPUT
?>
<form method="get">
Password: <input type="text" name="p" autocomplete="off" value="<?=$p?>" />
<input type="submit" name="_go" value="go" />
</form>
 
<?php
if (empty($_GET)) { die(); }
 
 
// PROCESS THE GET STRING
$pw = $_GET["p"];
 
// ENCRYPT THE GET STRING
$pw_encrypted = md5($pw);
if ($pw_encrypted == md5('Cat')) { echo "<br /><br />$pw = $pw_encrypted GOOD MATCH\n"; die(); }
if ($pw_encrypted == md5('Dog')) { echo "<br /><br />$pw = $pw_encrypted GOOD MATCH\n"; die(); }
if ($pw_encrypted == md5('dog')) { echo "<br /><br />$pw = $pw_encrypted GOOD MATCH\n"; die(); }
 
echo "<br /><br />$pw = $pw_encrypted NO MATCH \n";

Open in new window

0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1200 total points
ID: 26067362
This would be stronger and would allow for a larger vocabulary.  The "magic" part of this would be to deal with this field:

        $this->key = 'quay';

You would want some way to pass that to the foreign server without having it be detected by the owners of the foreign server - not  likely to be an easy task.
<?php // RAY_crypt.php
error_reporting(E_ALL);
 
class Encryption
{
    private $eot;
    private $key;
    private $ivs;
    private $iv;
 
    public function __construct()
    {
        $this->eot = '___EOT'; // END OF TEXT DELIMITER
        $this->key = 'quay';
        $this->ivs = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $this->iv  = mcrypt_create_iv($this->ivs);
    }
 
    public function Encrypt($text)
    {
        $text .= $this->eot; // APPEND END OF TEXT DEIMITER
        $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv);
        $data = base64_encode($data);
        return $data;
    }
 
    public function Decrypt($text)
    {
        $text = base64_decode($text);
        $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv);
        $data = explode($this->eot, $data); // REMOVE END OF TEXT DELIMITER
        return $data[0];
    }
}
 
// INSTANTIATE THE CLASS
$crypt = new Encryption();
 
// INITIALIZE VARS FOR LATER USE IN THE HTML FORM
$encoded = '';
$decoded = '';
 
// IF ANYTHING WAS POSTED
if (!empty($_POST["clearstring"]))
{
    $encoded = $crypt->Encrypt($_POST["clearstring"]);
    echo "<br/>{$_POST["clearstring"]} YIELDS "; var_dump($encoded);
}
 
if (!empty($_POST["cryptstring"]))
{
    $decoded = $crypt->Decrypt($_POST["cryptstring"]);
    echo "<br/>{$_POST["cryptstring"]} YIELDS "; var_dump($decoded);
}
 
?>
<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>

Open in new window

0
 

Author Comment

by:G_API
ID: 26067402
Grate, thank you all for your useful comments, Mr Ray_Paseur, Thanks for the code, but as you know the words for example cat, is readable to the customer as it will be in his PHP file and then he can figure out what is the password. I don't have any control in customer server which I will only send the PHP file to him.
Regards
0
 
LVL 34

Assisted Solution

by:Beverley Portlock
Beverley Portlock earned 200 total points
ID: 26067741
Ok - make an adaption of Ray's MD5 idea like so. Agree an MD5 algorithm that takes a random number in the range 1 to a billion. This is then mixed with a passphrase which is secret to produce the MD5 and the the MD5 and the random number are both sent along with the command.

So you decide that the passphrase will be "my big secret" then you can generate a key like so

$number = mt_rand(1, 1000000000);
$md5key = md5( $number . "my big secret" );

Then you run the command

http://the.remote.server.com/myscript.php?number=123677&md5key=14ad5263da95251524115326&myCommand=send-emails

then the remote server looks at the number, puts it into the formula

$checkMd5 = md5( $_GET['number'] . "my big secret")

and compares this md5 with the one passed

if ( $newMd5 == $_GET['md5key'] )
    ... command is from a valid sender

This way a new key is used every time a command is sent and since only authorised people know both the algorithm and the key phrase value then you have a high degree of confidence that the sender is valid. If you are worried about people storing a key / md5 pair then build a date into it

$number = mt_rand(1, 1000000000);
$md5key = md5( $number . "my big secret"  . date("Y-m-d h");

will give the key a life time of one hour. Using two randoms means that keys are virtually one-offs

$number1 = mt_rand(1, 1000000000);
$number2 = mt_rand(1, 1000000000);
$md5key = md5( $number1 . "my big secret" . $number2 . date("Ymd h") . $number1 );

http://the.remote.server.com/myscript.php?number1=123677&number2=7665273md5key=14ad5263da95251524115326&myCommand=send-emails

0
 
LVL 11

Assisted Solution

by:VanHackman
VanHackman earned 200 total points
ID: 26067816

I think  that the best way to do that is using Web  Services.

I mean, as I can understand you are trying to protect the information from the customer (who have full control of his server), so using a secure protocol with HTTPs/SSL will help but no for what do you need, because that kind of protection will prevent that your information could be access for attackers out of the server, no to prevent that your customer can access to the information that is transmitted over the secure protocol.  U_U

So, What options do you have?

1- The easy one: use the method that suggest  Ray_Paseur  AND obfuscate your code... so even your customer can open your scripts he will not be able to understand what are you doing or make some modification on your system.

2- Something more complicated: implement a Web Service that require authentication to use it, and put the Web Client in the Customers Server, so you will have the control over most of the process, and could use a algorithm like:

      a- The Web Client on your customer server make a request.
      b- The Web Service in your Host, attend the request and ask for a username/password.
      c- The Web Client log in to the service.
      d- The Web Service start to transmitting the data encrypted.
      e- The Web Service stop transmitting and send a Key.
      f- The Web Client Decrypt the information using the Key provided for the Web Service.
      g- The Connection between the servers is closed.

And, of course, you can obfuscate the Web Client Implementation to have the advantage described in the point 1.

Hope that my idea helps you!.
0
 
LVL 17

Expert Comment

by:CSecurity
ID: 26067858
@gr8gonzo, I'll give you an RSA key pay, no no... Just I'll give you a 250 digit number, try to factor it and find it's both prime factors, huh? Forget it man! It's simply impossible
0
 
LVL 17

Expert Comment

by:CSecurity
ID: 26067875
* I means key pair.

@G_API, also you can simply encrypt it with a fixed key and an encryption algorithm like AES, then change the key in both sides some often, huh?
0
 

Author Closing Comment

by:G_API
ID: 31667037
Thank you all :)
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 26067963
@CSecurity - I'm not saying it's trivial to crack, but it's not 100% uncrackable. They used to say 128-bit encryption could never be cracked, either. Again, it wasn't trivial, but where there's a will, there's a way. It's just a matter of who has the will. :)
0
 
LVL 17

Expert Comment

by:CSecurity
ID: 26068002
I have the will, I've ruined my life for a year, but you can't crack an RSA key pair when for example you have an E with 300-400 digit and N modulus with 200-300 digit, you should forget it. It's really really really impossible to do it. Mathematically impossible, logically.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 26068434
Just because you haven't been able to do it doesn't mean that it's impossible. I'm not debating how difficult it might be, either. Nor am I trying to be a snob about security.

The big picture of this question was to figure out a way to do something securely. Given that security was the important thing here, saying that there is a way to encrypt something in a way that is completely, 100% uncrackable may give the asker a false sense of "eternal security." It's important that people revisit their security solutions from time to time to make sure that they are staying secure, and not just relying on an idea that something will never be cracked.

Given that a roughly 400-bit RSA key was cracked with a LOT of horsepower back in 1994, it's just a matter of time until a 1024-bit key pair is cracked, and as computers continue to exponentially increase in power, it will become less and less difficult to do and will require a smaller quantity of computers.

The computer I have today can crack a simple ZIP password in a single day using a brute-force approach. The computer I had 8 years ago would have taken months, if not years, to do the same. I'm just trying to illustrate that anything that seems mathematically impossible today might be feasible in a year or two.

And again, I'm only saying all this because this question was about security. I probably wouldn't have commented if it had been a comment on an unrelated topic, but people tend to grab onto concepts like "100%" and get illogical ideas stuck in their head about something being bulletproof, and then they become lax in other areas of security. It's important for people who are asking about security to know the difference between unlikely and impossible.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 26068461
I should also point out that I'm fully aware that it's very unlikely that G_API's customer would go through the trouble of assembling a large network of computers running 24 hours a day to crack the RSA key pair or anything like that. Like I said, I'm not really a security snob who throws practicality out the window.

I'm just wary of G_API taking an idea with him to future projects where security may be even more paramount, and perhaps when cracking such a key pair is not so unlikely (perhaps by then, there will be a better, different way of doing things), or becoming so reliant on something being uncrackable that he neglects to take other measures to protect the key itself. Good security is a combination of good technology and good habits.
0
 
LVL 17

Expert Comment

by:CSecurity
ID: 26068474
Again I say, mathematically, cracking 400 digit RSA is impossible. Go to see what GMP forum are talking about. Literally, that's impossible. For the asker who's not going to deal with greatest hackers or greatest code breakers of the world, that would be 100%.

I can tell to rest of the world also 100%. I have a 17 RSA key, all is same length. Nearly 400 digit. If anyone in the world can crack it, I'm ready to pay a good money for it.

I tried that on a lot of forums, I tried that myself, with a lot of computers... Anyway! Forget it, I already left that stuff... Just again I do emphasize, nobody can crack 400 digit RSA key. Let's leave 400-digit. Why 400 digit? We can have a 1024 digit N and E for our RSA. I say, that's impossible to crack even using BlueGen or more powerful computers. For more discussion, goto GMP forum and Math experts will prove it to you. Here is not suitable.

0
 
LVL 17

Expert Comment

by:CSecurity
ID: 26068497
if this is a 1536 bit RSA key it will be betwwen 21535 (=1.205*10462) and 21536 (=2.410*10462). Since we assume its RSA key it will be 2 factors of 232 digits each, so lowest of the 2 factors will be between 1.000*10231 and 1.553*10231 (which is squareroot of 21536 or 2768).

The number of primes between x = 1.000*10231 and y = 1.553*10231 is roughly:
y / ln y - x / ln x = 2.916*10228 - 1.880*10228 = 1,036*10228

So 1,036*10228 primes to trialdivide. Lets say we wanted to be done before the sun explodes in about 5 billion years, we would have to test:
1,036*10228 / ( 5*109 yr * 31536000 sec/yr) = 6.57 * 10210 numbers every second or 3.5*10167 numbers every planck time (5.39*10-44 sec), which is the smallest time interval that has any meaning.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 26068700
-shrug- Over and over again, people (often times, "math experts") have said X is impossible, only to have it proven possible later with new theories and better technology. History has always been the best indicator of the future - don't ignore it. I'll leave that as my final comment on this - this is going off on a pretty wide tangent.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26071584
It is impossible for man to fly.  This is a well known fact, and the historical record proves it.  Quoting from the record, http://www.1902encyclopedia.com/A/AER/aeronautics-04.html

Having constructed a set of wings, composed of various plumage, he undertook from the walls of Stirling Castle to fly through the air to France. This feat he actually attempted, but he soon came to the ground, and broke his thigh-bone by the violence of the fall - an accident he explained by asserting that the feathers of some fowls were employed in his wings, and that these had an affinity for the dunghill, whereas, if composed solely of eagles' feathers, they would have been attracted to the air.

And there is this, too.
http://www.the-impossible-project.com/
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 26071893
There are two things that need to be distinguished here - those things which are impossible and those things which are computationally impracticable.

The two are not the same.

The cracking of a 400 digit RSA is possible with enough time and effort, but it is at present computationally impracticable if the time required to do it would be (say) 1000 years. It is nonetheless do-able.

On the other hand, the number 4 can be calculated by an infinite number of combinations - 2x2, 4x1 8x0.5, etc and with no further information I cannot say which pair of numbers where used so determining those original number is impossible rather than impracticable.

For the interested reader I suggest some reading on computational complexity and NP-completeness

http://en.wikipedia.org/wiki/NP-complete

0

Featured Post

 The Evil-ution of Network Security Threats

What are the hacks that forever changed the security industry? To answer that question, we created an exciting new eBook that takes you on a trip through hacking history. It explores the top hacks from the 80s to 2010s, why they mattered, and how the security industry responded.

Question has a verified solution.

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

Phishing emails are a popular malware delivery vehicle for attack.  While there are many ways for an attacker to increase the chances of success for their phishing emails, one of the most effective methods involves spoofing the message to appear to …
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
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…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

864 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