PHP code example of krak / hmac

1. Go to this page and download the library: Download krak/hmac library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

krak / hmac example snippets




use Krak\Hmac\Psr7HmacRequest,
    Krak\Hmac\HmacKeyPair,
    Krak\Hmac\ArrayHmacKeyPairProvider;

use function Krak\Hmac\hmac_sign_request,
    Krak\Hmac\hmac_auth_request;

// create the key pair of public and private keys
$keypair = new HmacKeyPair('public-key', 'private-key');

// wrap your request with the appropriate HmacRequest wrapper
$request = new Psr7HmacRequest($psr7_request);

// create the signer with default configuration
$sign = hmac_sign_request();

// sign the request
$request = $sign($request, $keypair);

// create a key pair provider for looking up the key pair used for the request
$provider = new ArrayHmacKeyPairProvider([$keypair]);

// we can authenticate a request now, by creating the authenticator with the
// same config as the signer (they need to match exactly)
$auth = hmac_auth_request($provider);

// authenticate the request
var_dump($auth($request));
// output: bool(true)



use Krak\Hmac;

$config = Hmac\HmacConfig::create([
    'scheme' => 'CustomHmac', // authentication scheme. Authorization: <scheme> <public_key>:<hash>
    'hasher' => new Hmac\StdHmacHasher(), // any HmacHasher instance, defaults to Base64HmacHasher(StdHmacHasher)
    'hs_gen' => hmac\hmac_hashed_hs_gen(), // any hash string generator function
    'time_gen' => hmac\hmac_date_time_gen() // any time_gen function for generating a unit of time
    'time_header' => 'Date',
    'auth_header' => 'Authorization',
]);

$sign = hmac\hmac_sign_request($config);
$auth = hmac\hmac_auth_request($provider, $config);



function concat_hs_gen() {
    return function(Krak\Hmac\HmacRequest $req, $time) {
        return $req->getUri() . $time;
    };
}



use GuzzleHttp\HandlerStack,
    GuzzleHttp\Client,
    Krak\Hmac\HmacKeyPair;
use function Krak\Hmac\Provider\guzzle_hmac_middleware,
    Krak\Hmac\hmac_psr7_sign_request,

$handler = HandlerStack::create();
$handler->push(guzzle_hmac_middleware(hmac_psr7_sign_request(), $keypair));
$client = new Client(['handler' => $handler]);

hmac_sign_request(HmacConfing = null);
hmac_psr7_sign_request(HmacConfing = null);
hmac_psr7_sign($sign);