Home > Dev > Crypto > HMAC (Hash-Based Message Authentication Code)

HMAC (Hash-Based Message Authentication Code)

This code snippet shows how to generate and verify HMACs.

function generate_hmac($data, $key) {
    return hash_hmac('sha256', $data, $key);
}

function verify_hmac($data, $key, $hmac) {
    $calculated_hmac = generate_hmac($data, $key);
    return hash_equals($calculated_hmac, $hmac);
}

// Usage example
$key = 'your-hmac-key';
$data = 'This is some data';
$hmac = generate_hmac($data, $key);
$is_valid = verify_hmac($data, $key, $hmac);

echo "HMAC: " . $hmac . "\n";
echo "Is Valid: " . ($is_valid ? 'Yes' : 'No') . "\n";
Back