3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * SMS Signin Gateway - HMAC class * @author adrian7 (adrian@studentmoneysaver.co.uk) * @version 1.1 */ /** * Generates/Validates HMAC signatures * Class HMAC * @link http://signin.studentmoneysaver.co.uk/docs/#API * @package App\Library */ class HMAC{ /** * Timezone */ const TZ = 'UTC'; /** * Cypher/algorithm to use * @see hash_algos() */ const CYPHER = 'sha256'; /** * Time frame in seconds, in which a message is considered valid */ const TIMEFRAME = 300; /** * Internal time format */ const TIME_FORMAT = 'Y-m-d H:i:s'; /** * Verifies a HMAC signature * @param $data * @param $signature * @param $privateKey * @param $timestamp * * @return bool */ public static function verify($data, $signature, $privateKey, $timestamp){ $now = self::timestamp(self::TZ); $tmin = ( $now - ( self::TIMEFRAME/2 ) ); $tmax = ( $now + ( self::TIMEFRAME/2 ) ); if( ( $timestamp < $tmin ) or ( $timestamp > $tmax ) ) return false; //out of time range $data = strval( $data ); $computed_sig = self::signature($data, $privateKey, $timestamp); return $signature == $computed_sig; } /** * Generates a HMAC signature * @param $data * @param $privateKey * @param null $timestamp * * @return string */ public static function signature($data, $privateKey, $timestamp=null){ $timestamp = empty($timestamp) ? self::timestamp(self::TZ) : intval($timestamp); $data = strval( $data ); $sig = base64_encode( hash_hmac(self::CYPHER, $data, $privateKey . '::' . date(self::TIME_FORMAT, $timestamp), true) ); echo "Time: " . $timestamp; return $sig; } /** * Generates timestamp based on timezone * @param string $tz * * @return int */ public static function timestamp($tz='UTC'){ $tz = new \DateTimeZone($tz); return date_create(NULL, $tz)->getTimestamp(); } /** * Validates a hash algorithm * @param $algo * @see hash_algos() * @return bool */ public static function isValidHashAlgo($algo){ $algos = hash_algos(); return in_array($algo, $algos); } } $timestamp = empty($timestamp) ? HMAC::timestamp(HMAC::TZ) : intval($timestamp); $url = "https://signin.studentmoneysaver.co.uk/api/?onSuccess=https%3A%2F%2Fwww.google.si%2Fsearch%3Fq%3Dsuccess&onFail=https%3A%2F%2Fwww.google.si%2Fsearch%3Fq%3Dfail&apikey=test-Yr82f2DowCdxRumRwAD8r66KMFF4GWDm&timestamp=$timestamp"; echo "Signature: " . HMAC::signature( $url, 'NP8T2NY2SR0XTNZ5', $timestamp);

preferences:
63.42 ms | 402 KiB | 5 Q