daxko / dax-signature-validation

0 stars 1 forks source link

Add PHP Example & Translation #1

Open froboy opened 4 years ago

froboy commented 4 years ago

There are a number of pieces here that don't translate directly to PHP so in addition to providing an example it might be good to translate some of the instructions too.

A few things:

Here's a really rough code snippet that I tested on http://phptester.net/

<?php

// Mock a call in Postman or similar and enter the values here.
$dax_expiration = "";
$status = "";
$area_id = "";
$validation_secret = "";
$dax_signature = "";

// Get the date in milliseconds.
$now = round(microtime(true)*1000);
if ($now > $dax_expiration) {
    print nl2br("wrong time \n");
}

// Concatenate the strings together.
$input_string = $dax_expiration . $status . $area_id;

// Convert the secret from hex to bin, then use it to calculate our hash
// and upper-case it, as PHP returns lower by default.
$our_signature = strtoupper(hash_hmac("sha256", $input_string, hex2bin($validation_secret)));

print nl2br("Input: $input_string \n");
print nl2br("Our sig: $our_signature \n");
print nl2br("Their sig: $dax_signature \n");

// Use hash_equals for a timing attack safe string comparison.
print hash_equals($our_signature, $dax_signature) ? "True" : "False";
froboy commented 4 years ago

Here's a much cleaner function to validate:

/**
   * Validate Daxko Barcode signature as per instructions here
   * https://github.com/daxko/dax-signature-validation.
   *
   * @param string $dax_expiration
   * @param string $status
   * @param string $area_id
   * @param string $validation_secret
   * @param string $dax_signature
   *
   * @return bool
   *   Whether the signature is validated or not.
   */
  private function validDaxSignature($dax_expiration, $status, $area_id, $validation_secret, $dax_signature) {

    $now = round(microtime(true)*1000);
    if ($now > $dax_expiration) {
      return FALSE;
    }

    $input_string = $dax_expiration . $status . $area_id;
    $key = hex2bin($validation_secret);
    $our_signature = strtoupper(hash_hmac("sha256", $input_string, $key));

    return hash_equals($our_signature, $dax_signature);
  }