Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
mongkok
committed
May 3, 2020
1 parent
c371114
commit b37b2ae
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
<?php | ||
|
||
namespace Postpay\Http; | ||
|
||
class Signature | ||
{ | ||
/** | ||
* @const int Default tolarence in seconds. | ||
*/ | ||
const DEFAULT_TOLERANCE = 300; | ||
|
||
/** | ||
* Verifies the signature header. | ||
* | ||
* @param string $payload | ||
* @param string $header | ||
* @param string $secret | ||
* @param int $tolerance | ||
* | ||
* @return bool | ||
*/ | ||
public static function verify( | ||
$payload, | ||
$header, | ||
$secret, | ||
$tolerance = self::DEFAULT_TOLERANCE | ||
) { | ||
list($timestamp, $signature) = explode(':', trim($header), 2); | ||
|
||
if (!is_numeric($timestamp) || empty($signature) || | ||
(($tolerance > 0) && (abs(time() - $timestamp) > $tolerance))) { | ||
return false; | ||
} | ||
$expected = hash_hmac('sha256', "{$timestamp}:{$payload}", $secret); | ||
return hash_equals($expected, $signature); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
<?php | ||
|
||
namespace Postpay\Tests\Http; | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Postpay\Http\Signature; | ||
|
||
class SignatureTest extends TestCase | ||
{ | ||
public function testVerify() | ||
{ | ||
$timestamp = time(); | ||
$signature = hash_hmac('sha256', "{$timestamp}:", 'secret'); | ||
|
||
$result = Signature::verify('', "{$timestamp}:{$signature}", 'secret'); | ||
self::assertTrue($result); | ||
} | ||
|
||
public function testVerifyHeaderError() | ||
{ | ||
$result = Signature::verify('', ':', 'secret'); | ||
self::assertFalse($result); | ||
} | ||
|
||
public function testVerifyToleranceError() | ||
{ | ||
$timestamp = time() - Signature::DEFAULT_TOLERANCE - 1; | ||
$signature = hash_hmac('sha256', "{$timestamp}:", 'secret'); | ||
|
||
$result = Signature::verify('', "{$timestamp}:{$signature}", 'secret'); | ||
self::assertFalse($result); | ||
} | ||
} |