yiisoft/yii2 · error · InvalidConfigException

Failed to generate HMAC with hash algorithm:

Error message

Failed to generate HMAC with hash algorithm: 

What it means

Security::validateData() first computes a probe HMAC of the empty string with the configured macHash purely to learn the digest length; if that probe fails the method cannot even parse the payload and throws InvalidConfigException before any comparison. The triggers are identical to hashData(): a macHash unknown to the hash extension. Tampered data or data signed under a different macHash does not raise this — those cases return false.

Source

Thrown at framework/base/Security.php:378

     * Validates if the given data is tampered.
     * @param string $data the data to be validated. The data must be previously
     * generated by [[hashData()]].
     * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
     * function to see the supported hashing algorithms on your system. This must be the same
     * as the value passed to [[hashData()]] when generating the hash for the data.
     * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]].
     * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
     * of lowercase hex digits only.
     * hex digits will be generated.
     * @return string|false the real data with the hash stripped off. False if the data is tampered.
     * @throws InvalidConfigException when HMAC generation fails.
     * @see hashData()
     */
    public function validateData($data, $key, $rawHash = false)
    {
        $test = @hash_hmac($this->macHash, '', '', $rawHash);
        if (!$test) {
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
        }
        $hashLength = StringHelper::byteLength($test);
        if (StringHelper::byteLength($data) >= $hashLength) {
            $hash = StringHelper::byteSubstr($data, 0, $hashLength);
            $pureData = StringHelper::byteSubstr($data, $hashLength, null);

            $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);

            if ($this->compareString($hash, $calculatedHash)) {
                return $pureData;
            }
        }

        return false;
    }

    /**
     * Generates specified number of random bytes.

View on GitHub (pinned to 66f00d18a2)

Solutions

  1. Fix macHash to the default 'sha-256' or a name listed by hash_hmac_algos() in the validating runtime
  2. Assert macHash validity at bootstrap in every environment that signs or validates
  3. Keep signer and validator components configured identically for shared data
  4. Treat a false return (not this exception) as the signal for re-signing data after legitimate algorithm changes

Example fix

// before (config only on the validating side)
'components' => [
    'security' => ['macHash' => 'sha3512'], // typo → probe HMAC fails → exception
],

// after
'components' => [
    'security' => ['macHash' => 'sha-256'],
],
$pureData = Yii::$app->security->validateData($signed, $key);
if ($pureData === false) {
    // tampered or signed under a different key/macHash — handle as invalid
}
Defensive patterns

Strategy: validation

Validate before calling

if (!in_array(Yii::$app->security->macHash, hash_hmac_algos(), true)) {
    throw new \RuntimeException('macHash not supported: ' . Yii::$app->security->macHash);
}
$pureData = Yii::$app->security->validateData($signed, $key);
if ($pureData === false) {
    // tampered or signed under a different key/macHash
}

Try / catch

try {
    $pureData = Yii::$app->security->validateData($signed, $key);
} catch (\yii\base\InvalidConfigException $e) {
    // probe HMAC failed: macHash unsupported — config fix required before any data can validate
}

Prevention

When it happens

Trigger: Reading hashData-signed cookies or tokens with a Security component whose macHash was changed to a misspelled or unavailable algorithm; environments drifted so only the validating side has the bad value; deploying a macHash change before re-issuing signed data is a related but distinct failure (returns false, not this exception).

Common situations: Signed cookie validation after security config changes; API token verification across services with separately managed configs; staging vs production hash availability differences.

Related errors


AI-assisted analysis of yiisoft/yii2@66f00d18a2 (2026-08-17). Data as JSON: /api/errors/151ddb2df9e75982. Report an issue: GitHub.