Php – securely send data from one site to another

data-transferphpphp4security

I am going to post some data from one website to another website. I need a way for the receiving website to be sure that the data was sent from the sending website and not sent by some other malicious user. I am using PHP4.

How can I do this?

Thanks!

Best Solution

For a PHP-only solution:

If you can keep a secret (on both ends), then you can use a self-implemented variant (yes, a variant) of Keyed-Hash Message Authentication Code (HMAC or KHMAC).

The concept is that if you have the same secret on both ends, you can hash (message+secret) on the sending end, and hash (message+secret) on the recieving end. If the hashes match, then you have a valid message.

The secret is the key (pun intended). Because without the secret, it is infeasible that an attacker could alter the message AND generate a new hash that will verify on the receiving end.

Here is some example PHP code:

// On the sending end:
define('SECRET', '12734981273912379128739128739127938794729327492');
$message = 'your-message';
$packet = $message . sha1($message . SECRET);

// On the receiving end:
define('SECRET', '12734981273912379128739128739127938794729327492');
$message = substr($packet, 0, -40);
if(sha1($message . SECRET) != substr($packet, -40))
    throw new Exception("Message Authentication failed!")
else
    do_something_with($message);

If you wanted additional security from a hacker re-posting the same message, you could add a random request identifier to each request, and ensure that the same hash is NEVER accepted.

DISCLAIMER: this as with all security sensitive code should be peer reviewed and verified before being trusted with sensitive data. Do through research on the topic, or better yet, use an existing library that handles this type of verification+authentication.