Neos\Flow\Security\Cryptography\HashService::validateAndStripHmac PHP Method

validateAndStripHmac() public method

Tests if the last 40 characters of a given string $string matches the HMAC of the rest of the string and, if true, returns the string without the HMAC. In case of a HMAC validation error, an exception is thrown.
See also: validateHmac()
public validateAndStripHmac ( string $string ) : string
$string string The string with the HMAC appended (in the format 'string')
return string the original string without the HMAC, if validation was successful
    public function validateAndStripHmac($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentForHashGenerationException('A hash can only be validated for a string, but "' . gettype($string) . '" was given.', 1320829762);
        }
        if (strlen($string) < 40) {
            throw new InvalidArgumentForHashGenerationException('A hashed string must contain at least 40 characters, the given string was only ' . strlen($string) . ' characters long.', 1320830276);
        }
        $stringWithoutHmac = substr($string, 0, -40);
        if ($this->validateHmac($stringWithoutHmac, substr($string, -40)) !== true) {
            throw new InvalidHashException('The given string was not appended with a valid HMAC.', 1320830018);
        }
        return $stringWithoutHmac;
    }

Usage Example

 /**
  * Extracts the WidgetContext from the given $httpRequest.
  * If the request contains an argument "__widgetId" the context is fetched from the session (AjaxWidgetContextHolder).
  * Otherwise the argument "__widgetContext" is expected to contain the serialized WidgetContext (protected by a HMAC suffix)
  *
  * @param Request $httpRequest
  * @return WidgetContext
  */
 protected function extractWidgetContext(Request $httpRequest)
 {
     if ($httpRequest->hasArgument('__widgetId')) {
         return $this->ajaxWidgetContextHolder->get($httpRequest->getArgument('__widgetId'));
     } elseif ($httpRequest->hasArgument('__widgetContext')) {
         $serializedWidgetContextWithHmac = $httpRequest->getArgument('__widgetContext');
         $serializedWidgetContext = $this->hashService->validateAndStripHmac($serializedWidgetContextWithHmac);
         return unserialize(base64_decode($serializedWidgetContext));
     }
     return null;
 }
All Usage Examples Of Neos\Flow\Security\Cryptography\HashService::validateAndStripHmac