Gawet
Gawet

Reputation: 315

PHP - cURL : How to safely send data to another server using cURL

I'm trying to send some data from server(A) to server(B) via cURL and then, putting the said data into a database or deleting from them, depending on the case. The thing is I want to secure it and to be sure not everyone can put anything he wants in the database by accessing to the server(B). So I've put a hash with the other data:

<?php
    $url = "https://serverB/test.php";
    $hash = hash('sha512','UPbztBfJEY7FjDjUZ7kd');//Don't mind the sha512 instead of bcrypt, both my servers aren't working with bcrypt.

    $fields = array(
        'ref' => 'toasty',
        'name' => 'toasta'
        'hash'=> $hash
    );

    $fields_string = http_build_query($fields);

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_exec($ch);
?>

And then, we verify it on the other server:

<?php
    $hash=(array_key_exists('hash',$_POST))?$_POST['hash']:'';
    if($hash==hash('sha512','UPbztBfJEY7FjDjUZ7kd')){
        //Insert the data into the database
    }
?>

But is it really secure? If someone can read through what I'm sending, even if the $hash is well, hashed, he could really just send anything he wants by simply typing the hashed password, since the verification would work.

is it enough ? How can I do better ?

Feel free to ask me for further info I would have missed, thanks !

Upvotes: 0

Views: 1460

Answers (1)

Mark_1
Mark_1

Reputation: 643

You need to hash the data to make sure that it hasn't been changed in transit and you can use your secret key to make sure that only authorised parties can generate a valid hash. So your sending code might look like this.

  $yourSecretKey = 'UPbztBfJEY7FjDjUZ7kd';
  $fields = array(
      'ref' => 'toasty',
      'name' => 'toasta'
       );
  $hash = hash('sha512', $yourSecretKey . serialize($fields));

  $fields['hash'] = $hash;

And at the receiving end you need to extract the hash from the data, use the secret key to hash the other data fields and check the generated hash against your extracted hash.

foreach ($_POST as $key => $value) {
    if ($key === 'hash') {     // Checksum value is separate from all other fields and shouldn't be included in the hash
        $checksum = $value;
    } else {
        $input[$key] = $value;
    }
}

$hash = hash('sha512', $yourSecretKey . serialize($input));
if ($hash === $checksum) {
    $valid = true;
} else {
    $valid = false;
}

Upvotes: 1

Related Questions