How can I create a shared-secret voucher code system between 2 independent servers?

折月煮酒 提交于 2019-12-04 09:56:27

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';
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!