Skip to content

Commit

Permalink
Add SignNonce
Browse files Browse the repository at this point in the history
  • Loading branch information
kiankamgar committed Apr 13, 2024
1 parent 6fc808d commit 513b6af
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/Helpers/SignHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace KianKamgar\MoadianPhp\Helpers;

use Exception;

class SignHelper
{
public static function base64url_encode(string $data): string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

/**
* @throws Exception
*/
public static function getCertificate(string $certificatePath): string
{
$content = self::getFileContents($certificatePath);

return strtr($content, [
'-----BEGIN CERTIFICATE-----' => '',
'-----END CERTIFICATE-----' => '',
"\n" => '',
"\r" => ''
]);
}

/**
* @throws Exception
*/
public static function getPrivateKey(string $privateKeyPath): string
{
return self::getFileContents($privateKeyPath);
}

/**
* @throws Exception
*/
private static function getFileContents(string $fileName): string
{
$content = file_get_contents($fileName);

if (empty($content)) {

throw new Exception('Certificate file not found');
}

return $content;
}
}
75 changes: 75 additions & 0 deletions src/Services/SignNonce.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

namespace KianKamgar\MoadianPhp\Services;

use DateTime;
use DateTimeZone;
use Exception;
use KianKamgar\MoadianPhp\Helpers\SignHelper;

class SignNonce
{
public function __construct(
private string $privateKey,
private string $x5c,
private string $nonce,
private string $clientId,
)
{}

/**
* @throws Exception
*/
public function getToken(): string
{
$header = $this->getHeader();
$payload = $this->getPayload();
$data = $header . '.' . $payload;
$signature = $this->getSignature($data);

return $data . '.' . $signature;
}

/**
* @throws Exception
*/
private function getHeader(): string
{
$data = [
'alg' => 'RS256',
'x5c' => [$this->x5c],
'sigT' => $this->getSigT(),
'typ' => 'jose',
'crit' => ['sigT'],
'cty' => 'text/plain'
];

return SignHelper::base64url_encode(json_encode($data));
}

private function getPayload(): string
{
$data = [
'nonce' => $this->nonce,
'clientId' => $this->clientId
];

return SignHelper::base64url_encode(json_encode($data));
}

private function getSignature(string $data): string
{
openssl_sign($data, $signature, openssl_pkey_get_private($this->privateKey), OPENSSL_ALGO_SHA256);

return SignHelper::base64url_encode($signature);
}

/**
* @throws Exception
*/
private function getSigT(): string
{
return (new DateTime('now', new DateTimeZone('UTC')))
->format('Y-m-d\TH:i:s\Z');
}
}

0 comments on commit 513b6af

Please sign in to comment.