Given this workflow:
Server A
- User authenticates.
- User purchases randomly generated unique voucher code using shared secret to use an application on on server B.
Server B
- User authenticates.
- User inputs voucher code.
- Server B validates code is legitimate using shared secret
- 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
}
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:
- 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.
- User presents voucher to server B.
- 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';
}
来源:https://stackoverflow.com/questions/18219053/how-can-i-create-a-shared-secret-voucher-code-system-between-2-independent-serve