Skip to content

Instantly share code, notes, and snippets.

@Zegnat
Last active June 30, 2017 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zegnat/c22fea3c368217df2620654d90b7ca30 to your computer and use it in GitHub Desktop.
Save Zegnat/c22fea3c368217df2620654d90b7ca30 to your computer and use it in GitHub Desktop.
<?php
function create_signed_code($key, $message, $ttl = 31536000, $appended_data = '')
{
$expires = time() + $ttl;
$body = $message . $expires . $appended_data;
$signature = hash_hmac('sha256', $body, $key);
return dechex($expires) . ':' . $signature . ':' . $appended_data;
}
function verify_signed_code($key, $message, $code)
{
$code_parts = explode(':', $code, 3);
if (count($code_parts) !== 3) return false;
$expires = hexdec($code_parts[0]);
if (time() > $expires) return false;
$body = $message . $expires . $code_parts[2];
$signature = hash_hmac('sha256', $body, $key);
return $signature === $code_parts[1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment