Question

Given this workflow:

Server A

  1. User authenticates.
  2. User purchases randomly generated unique voucher code using shared secret to use an application on on server B.

Server B

  1. User authenticates.
  2. User inputs voucher code.
  3. Server B validates code is legitimate using shared secret
  4. Server B grants access to the application.

I need a way in PHP to implement the functions generateVoucherCode and validateVoucherCode as shown below:

Server A

$voucher = generateVoucherCode("someSharedSecret");

Server B

$isValid = validateVoucherCode($userInputtedCode, "someSharedSecret");
if($isValid) {
    // allow access to application
}
Was it helpful?

Solution

Validating legitimacy through a shared secret is what HMACs are for. You can generate a HMAC in PHP through hash_hmac. Your workflow would be:

  1. Server A generates an one-use code (in any manner you want) and calculates its HMAC. The pair of code + HMAC is given to the user as a voucher code.
  2. User presents voucher to server B.
  3. Server B isolates the one-use code from the voucher and independently calculates its HMAC using the shared secret. If the calculated HMAC matches the one in the voucher then the voucher is genuine.

Example voucher generation:

$secret = '$uper$ecret$tring';
$code = 'a pet unicorn';
$voucher = $code.'/'.hash_hmac('sha512', $code, $secret);

echo 'Your voucher is '.$voucher';

Example voucher verification:

$secret = '$uper$ecret$tring';
list ($code, $hmac) = explode('/', $voucher);
$verify_hmac = hash_hmac('sha512', $code, $secret);
if ($hmac === $verify_hmac) {
    echo 'Your voucher can be redeemed for '.$code';
}
else {
    echo 'Invalid voucher, sorry';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top