PHPackages                             mardy-git/hmac - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. mardy-git/hmac

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

mardy-git/hmac
==============

A keyed-Hash Message Authentication Code (HMAC). Used for application to application authentication.

3.0.0(5y ago)1211.9k↓41.1%3WTFPLPHPPHP &gt;=7.4

Since May 30Pushed 5y ago2 watchersCompare

[ Source](https://github.com/mardy-git/hmac)[ Packagist](https://packagist.org/packages/mardy-git/hmac)[ Docs](http://github.com/mardy-git/hmac)[ RSS](/packages/mardy-git-hmac/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (1)Versions (19)Used By (0)

Mardy-Git HMAC
==============

[](#mardy-git-hmac)

[![Build Status](https://camo.githubusercontent.com/d39c8629c6df0d45ab804d6897921aa740f38bc67b80af8fb35e4e66b4bac10b/68747470733a2f2f7472617669732d63692e6f72672f6d617264792d6769742f686d61632e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/mardy-git/hmac) | [![Bitdeli Badge](https://camo.githubusercontent.com/0db85e9d3f613e0a22218ec45094b22f6a0d84a8253c20bde910a9e894c74b9b/68747470733a2f2f64327765637a68766c38323376302e636c6f756466726f6e742e6e65742f6d617264792d6769742f686d61632f7472656e642e706e67)](https://bitdeli.com/free "Bitdeli Badge")

A simple lightweight HMAC generator and checker.

Currently this is used to authenticate applications to other applications.

NOTE
----

[](#note)

At the moment the Bcrypt adapter is broken on PHP 7. This is due to the changes in the password\_hash function. I will be working on a fix for this in v3 which will come out soon.

Installation
------------

[](#installation)

To install this use composer by adding

```
"mardy-git/hmac": "2.*"

```

to your composer.json file

Usage Example
-------------

[](#usage-example)

Generating the HMAC
-------------------

[](#generating-the-hmac)

```
use Mardy\Hmac\Manager;
use Mardy\Hmac\Adapters\Hash;
use Mardy\Hmac\Exceptions\HmacInvalidAlgorithmException;
use Mardy\Hmac\Exceptions\HmacInvalidArgumentException;

//there are several adapters available 'Bcrypt', 'Hash', 'HashHmac', 'HashPbkdf2'
//you can inject any of them into the manager, they all share the same interface
//With the Bcrypt adapter the num of iteration config is applied to the cost
$manager = new Manager(new Hash);

//you can use any of the Hash algorithms that are available on your environment
$config = [
    'algorithm' => 'sha256',
    'num-first-iterations' => 10,
    'num-second-iterations' => 10,
    'num-final-iterations' => 100,
];

//the private key used in both applications to ensure the hash is the same
$key = 'wul4RekRPOMw4a2A6frifPqnOxDqMXdtRQMt6v6lsCjxEeF9KgdwDCMpcwROTqyPxvs1ftw5qAHjL4Lb';

try {
    $manager->config($config);
} catch (HmacInvalidAlgorithmException $e) {
    //an HmacInvalidAlgorithmException can be caught here
    //"The algorithm ({$algorithm}) selected is not available"
}

//the secure private key that will be stored locally and not sent in the http headers
$manager->key($key);

//the data to be encoded with the hmac, you could use the URI for this
$manager->data('test');

//the current timestamp, this will be compared in the other API to ensure
$manager->time(microtime(true)); //use time() or micortime(true)

//encodes the hmac if all the requirements have been met
try {
    $manager->encode();
} catch (HmacInvalidArgumentException $e) {
    //an HmacInvalidArgumentException can be caught here
    //'The item is not encodable, make sure the key, time and data are set'
}

$hmac = $manager->toArray();

//these values need to be sent in the http headers of the request so they can
//be received by the api and used to authenticated the request
//$hmac = [
//    'data' => 'test-data', //perhaps the uri or other unique string related to the transaction
//    'time' => 1396901689,
//    'hmac' => 'f22081d5fcdc64e3ee78e79d235f67b2d1a54ba24be6da4ac537976d313e07cf119731e76585b9b22f789c6043efe1df133497483f559899db7d2f4398084b08',
//];
```

Validating the HMAC
-------------------

[](#validating-the-hmac)

```
use Mardy\Hmac\Manager;
use Mardy\Hmac\Adapters\Hash;
use Mardy\Hmac\Exceptions\HmacInvalidAlgorithmException;

//there are several adapters available 'Bcrypt', 'Hash', 'HashHmac', 'HashPbkdf2'
//you can inject any of them into the manager, they all share the same interface
//With the Bcrypt adapter the num of iteration config is applied to the cost
$manager = new Manager(new Hash);

//you can use any of the Hash algorithms that are available on your environment
$config = [
    'algorithm' => 'sha256',
    'num-first-iterations' => 10,
    'num-second-iterations' => 10,
    'num-final-iterations' => 100,
];

//the private key used in both applications to ensure the hash is the same
$key = 'wul4RekRPOMw4a2A6frifPqnOxDqMXdtRQMt6v6lsCjxEeF9KgdwDCMpcwROTqyPxvs1ftw5qAHjL4Lb';
$ttl = 2;

try {
    $manager->config($config);
} catch (HmacInvalidAlgorithmException $e) {
    //an HmacInvalidAlgorithmException can be caught here
    //"The algorithm ({$algorithm}) selected is not available"
}

//time to live, when checking if the hmac isValid this will ensure
//that the time with have to be with this number of seconds
$manager->ttl($ttl);

//the secure private key that will be stored locally and not sent in the http headers
$manager->key($key);

//get the HMAC values from the $_SERVER/request headers (and make sure you sanitise the values)
$hmac['data'] = filter_var($_SERVER['data'], FILTER_SANITIZE_STRING);
$hmac['time'] = filter_var($_SERVER['time'], FILTER_SANITIZE_STRING);
$hmac['hmac'] = filter_var($_SERVER['hmac'], FILTER_SANITIZE_STRING);

//the data to be encoded with the hmac, you could use the URI for this
$manager->data($hmac['data']);

//the current timestamp, this will be compared in the other API to ensure
$manager->time($hmac['time']);

//to check if the hmac is valid you need to run the isValid() method
//this needs to be executed after the encode method has been ran
if (! $manager->isValid($hmac['hmac'])) {
    http_response_code(401);
    echo 'Invalid credentials';
}
```

Using with Guzzle
-----------------

[](#using-with-guzzle)

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

There is now a plugin that will allow integration with guzzle 4+

```
use GuzzleHttp\Client;
use GuzzleHttp\Event\BeforeEvent;
use Mardy\Hmac\Plugin\HmacHeadersGuzzleEvent;
use Mardy\Hmac\Adapters\Hash;

//Using the HmacHeadersGuzzleEvent class you can automatically inject some headers
//directly into the guzzle request. This is far more convenient for those of us
//using dependency injection containers and means we don't have to do it manually
//each time \o/

$client = new Client;

$client->getEmitter()->on('before', function (BeforeEvent $event) {
    (new HmacHeadersGuzzleEvent(
        new Hash,
        'wul4RekRPOMw4a2A6frifPqnOxDqMXdtRQMt6v6lsCjxEeF9KgdwDCMpcwROTqyPxvs1ftw5qAHjL4Lb',
        'test-data',
        microtime(true)
    ))->onBefore($event);
});

$request = $client->createRequest('GET', 'http://www.google.com');
$client->send($request);
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~219 days

Recently: every ~511 days

Total

14

Last Release

1886d ago

Major Versions

v0.3.0 → v2.0.02014-04-11

v2.3.4 → 3.0.02021-03-20

PHP version history (3 changes)v0.1.0PHP &gt;=5.4

v2.2.1PHP &gt;=5.5

3.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/cd22019623ac7e0ed3b0680eb602a6794fbbd4467ba905fa3ab07bfc962069ce?d=identicon)[mic2100](/maintainers/mic2100)

---

Top Contributors

[![mardy-git](https://avatars.githubusercontent.com/u/4436586?v=4)](https://github.com/mardy-git "mardy-git (1 commits)")[![mic2100](https://avatars.githubusercontent.com/u/2852547?v=4)](https://github.com/mic2100 "mic2100 (1 commits)")[![rolies106](https://avatars.githubusercontent.com/u/1167249?v=4)](https://github.com/rolies106 "rolies106 (1 commits)")

---

Tags

Authenticationhashhmacpbkdf2guzzle-plugin

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mardy-git-hmac/health.svg)

```
[![Health](https://phpackages.com/badges/mardy-git-hmac/health.svg)](https://phpackages.com/packages/mardy-git-hmac)
```

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.6k136.0M248](/packages/league-oauth2-server)[league/oauth2-client

OAuth 2.0 Client Library

3.8k118.6M1.2k](/packages/league-oauth2-client)[google/auth

Google Auth Library for PHP

1.4k272.7M162](/packages/google-auth)[pragmarx/google2fa

A One Time Password Authentication package, compatible with Google Authenticator.

2.0k82.4M164](/packages/pragmarx-google2fa)[paragonie/sodium_compat

Pure PHP implementation of libsodium; uses the PHP extension if it exists

930131.6M155](/packages/paragonie-sodium-compat)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
