How to create a shared secret voucher system between two independent servers?

Given this workflow:

Server A

  • The user is authenticated.
  • A user buys a randomly generated unique voucher code using a shared secret to use the application on server B.

Server B

  • The user is authenticated.
  • User enters voucher code.
  • Server B verifies that the code is legal using a shared secret
  • Server B provides access to the application.

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

Server A

 $voucher = generateVoucherCode("someSharedSecret"); 

Server B

 $isValid = validateVoucherCode($userInputtedCode, "someSharedSecret"); if($isValid) { // allow access to application } 
+4
source share
1 answer

Validation through a shared secret - these are HMACs . You can create HMAC in PHP via hash_hmac . Your workflow will be as follows:

  • Server A generates a one-time code (in any way) and calculates its HMAC. The + HMAC code pair is provided to the user as a voucher code.
  • The user submits a voucher to server B.
  • Server B isolates the one-time code from the voucher and independently calculates its HMAC using a shared secret. If the calculated HMAC matches that of the voucher, then the voucher is genuine.

Example of receiving a voucher:

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

Example of checking a voucher:

 $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'; } 
+1
source

Source: https://habr.com/ru/post/1496914/


All Articles