Skip to content

Commit

Permalink
new signature service
Browse files Browse the repository at this point in the history
  • Loading branch information
hbhossein committed Oct 9, 2023
1 parent 0684a3a commit f377d09
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 52 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"guzzlehttp/guzzle": "^7.0",
"ramsey/uuid": "^4.2",
"symfony/cache": "^5.3|^6.0",
"phpseclib/phpseclib": "^3.0"
"phpseclib/phpseclib": "^3.0",
"firebase/php-jwt": "^6.9"
},
"autoload": {
"psr-4": {
Expand Down
75 changes: 24 additions & 51 deletions src/Services/SignatureService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,43 @@

namespace Jooyeshgar\Moadian\Services;

use Jooyeshgar\Moadian\Exceptions\MoadianException;
use Firebase\JWT\JWT;

class SignatureService
{
private string $privateKey;
private string $x5c;

public function __construct(string $privateKey)
public function __construct(string $privateKey, string $x5c)
{
$this->privateKey = $privateKey;
$this->x5c = $x5c;
}

public function sign(array $data, array $headers)
/**
* Converts and signs a PHP array to JWS string
*/
public function sign(array $payload, array $headers = [])
{
$text = $this->normalizer($data, $headers);
$signature = '';

if (openssl_sign($text, $signature, $this->privateKey, OPENSSL_ALGO_SHA256)) {
return base64_encode($signature);
}
else {
throw new MoadianException('Failed to sign the text with message ' . openssl_error_string());
if (empty($headers)) {
$headers = [
'alg' => 'RS256',
'x5c' => [$this->x5c],
'sigT' => Carbon::now()->toIso8601ZuluString(),
'typ' => 'jose',
'crit' => ['sigT'],
'cty' => 'text/plain'
];
}
}


public static function normalizer(array $data, array $headers): string
{
$data = $data + $headers;

$normalizedData = [];

$flatted = self::flattener($data);

ksort($flatted);
$segments = [];
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($headers));
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));

foreach ($flatted as $value) {
$signingInput = implode('.', $segments);
$signature = JWT::sign($signingInput, $this->privateKey, $headers['alg']);
$segments[] = JWT::urlsafeB64Encode($signature);

if (is_bool($value)) {
$value = $value ? 'true' : 'false';
}

if ($value === '' || $value === null) {
$value = '#';
}
elseif (str_contains($value, '#')){
$value = str_replace('#', '##', $value);
}

$normalizedData[] = $value;
}

return implode("#", $normalizedData);
}

private static function flattener(array $array, string $prefix = ''): array {
$flatted = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$flatted = array_merge($flatted, self::flattener($value, "$prefix.$key"));
}
else {
$flatted["$prefix.$key"] = $value;
}
}
return $flatted;
return implode('.', $segments);
}
}

0 comments on commit f377d09

Please sign in to comment.