How can I create a shared-secret voucher code syst

2020-07-18 05:12发布

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
}

1条回答
我命由我不由天
2楼-- · 2020-07-18 05:26

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';
}
查看更多
登录 后发表回答