Skip to content

Commit

Permalink
Added signature verification
Browse files Browse the repository at this point in the history
  • Loading branch information
mongkok committed May 3, 2020
1 parent c371114 commit b37b2ae
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/Http/Signature.php
@@ -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);
}
}
33 changes: 33 additions & 0 deletions tests/Http/SignatureTest.php
@@ -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);
}
}

0 comments on commit b37b2ae

Please sign in to comment.