Skip to content

Commit

Permalink
v1.3.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Luca Castelnuovo committed Apr 30, 2021
1 parent 213bc49 commit ad8dc6f
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 14 deletions.
15 changes: 10 additions & 5 deletions examples/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use CQ\Crypto\Exceptions\TokenException;
use CQ\Crypto\Token;

$key = random_bytes(32);
Expand All @@ -13,12 +14,16 @@
]
);

$decode = Token::decode(
key: $key,
givenToken: $token
);
try {
$decode = Token::decode(
key: $key,
givenToken: $token
);
} catch (TokenException) {
echo 'Token invalid';
}

echo json_encode([
'token' => $token,
'isValid' => $decode,
'payload' => $decode,
]);
11 changes: 11 additions & 0 deletions src/Crypto/Exceptions/TokenException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace CQ\Crypto\Exceptions;

use Exception;

final class TokenException extends Exception
{
}
29 changes: 20 additions & 9 deletions src/Crypto/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,46 @@

namespace CQ\Crypto;

use CQ\Crypto\Exceptions\TokenException;
use ParagonIE\Paseto\Exception\PasetoException;
use ParagonIE\Paseto\Keys\SymmetricKey;
use ParagonIE\Paseto\Protocol\Version2;

final class Token
{
private static function getKey(string $key): SymmetricKey
{
$hashedKey = hash(
algo: 'sha256',
data: $key
);

$shortenedKey = substr($hashedKey, 0, 32);

return new SymmetricKey(
keyMaterial: $shortenedKey
);
}

public static function create(string $key, array $data): string
{
return Version2::encrypt(
data: json_encode($data),
key: new SymmetricKey(
keyMaterial: $key
)
key: self::getKey(key: $key)
);
}

public static function decode(string $key, string $givenToken): bool | object
{
try {
$decryptedToken = Version2::decrypt(
$data = Version2::decrypt(
data: $givenToken,
key: new SymmetricKey(
keyMaterial: $key
)
key: self::getKey(key: $key)
);
} catch (PasetoException) {
return false;
throw new TokenException();
}

return json_decode($decryptedToken);
return json_decode($data);
}
}

0 comments on commit ad8dc6f

Please sign in to comment.