Sign a value with an HMAC of the hash service 

Changed in version 14.0

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\CMS\Core\Crypto\HashService 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\CMS\Core\Crypto\HashAlgo as its last argument. The enum provides SHA1, SHA256, SHA384, SHA512, SHA3_256, SHA3_384 and SHA3_512.

The methods still use HashAlgo::SHA1 as the default, because another default would invalidate every signature that an installation created before. Pass HashAlgo::SHA3_256 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:

  • HashService::hmac() returns the signature of a value.
  • HashService::appendHmac() returns the value with the signature attached to it.
  • HashService::validateHmac() compares a value with a signature and returns a boolean.
  • HashService::validateAndStripHmac() removes the signature from a value and returns the value without it. It throws an \TYPO3\CMS\Core\Exception\Crypto\InvalidHashStringException when the signature does not match, or when the value is shorter than the signature.
packages/my_extension/Classes/Service/DownloadLinkService.php
<?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,
    );
  }
}
Copied!