Given this workflow:
Server A
Server B
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
}
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:
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';
}