Sign a value with an HMAC of the hash service
Changed in version 14.0
TYPO3 Core signs cHash values, password reset tokens, file dump URLs, form protection tokens and session identifiers with SHA3-256 now. See Breaking: #106307 - Use stronger cryptographic algorithm for HMAC.
An HMAC proves that TYPO3 created a value itself. Add such a signature to a
value that leaves the installation and comes back later, for example a
parameter of a URL. The
\TYPO3\
creates and validates the signature.
The service builds the secret from the encryption key of the installation and from an additional secret that the caller passes. The additional secret must not be empty. Pass a value that names the purpose of the signature, for example the class that creates it.
Choose the algorithm with the HashAlgo enum
Every method takes a case of the enum
\TYPO3\
as its last argument. The enum provides SHA1, SHA256, SHA384,
SHA512, SHA3_, SHA3_ and SHA3_.
The methods still use Hash as the default, because another default
would invalidate every signature that an installation created before. Pass
Hash in new code. TYPO3 Core passes it since version 14.0.
Validate a value with the algorithm that signed it. Another algorithm produces another signature, and the validation fails.
Sign and validate a value with the hash service
The hash service provides four methods:
Hashreturns the signature of a value.Service:: hmac () Hashreturns the value with the signature attached to it.Service:: append Hmac () Hashcompares a value with a signature and returns a boolean.Service:: validate Hmac () Hashremoves the signature from a value and returns the value without it. It throws anService:: validate And Strip Hmac () \TYPO3\when the signature does not match, or when the value is shorter than the signature.CMS\ Core\ Exception\ Crypto\ Invalid Hash String Exception
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Service;
use TYPO3\CMS\Core\Crypto\HashAlgo;
use TYPO3\CMS\Core\Crypto\HashService;
final readonly class DownloadLinkService
{
public function __construct(private HashService $hashService) {}
public function createToken(int $fileUid): string
{
return $this->hashService->hmac(
(string)$fileUid,
self::class,
HashAlgo::SHA3_256,
);
}
public function isValidToken(int $fileUid, string $token): bool
{
return $this->hashService->validateHmac(
(string)$fileUid,
self::class,
$token,
HashAlgo::SHA3_256,
);
}
}