PHP code example of darkstrata / credential-check

1. Go to this page and download the library: Download darkstrata/credential-check 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/ */

    

darkstrata / credential-check example snippets




arkStrata\CredentialCheck\Client;
use DarkStrata\CredentialCheck\Crypto;

$client = new Client(['apiKey' => getenv('DARKSTRATA_API_KEY')]);

// $email and $password come from your login form and are only ever used here.
// 1. Hash the credential locally: SHA-256 of "email:password".
//    The plaintext email and password never leave this process.
$hash = Crypto::hashCredential($email, $password);

// 2. Check the hash. The SDK sends only the first 5 characters (the
//    k-anonymity prefix) to the API and compares the full hash locally.
$result = $client->checkHash($hash);

if ($result->found) {
    echo "WARNING: Credential found in breach!";
} else {
    echo "OK: Credential not found in known breaches";
}

$client = new Client([
    'apiKey'        => 'your-api-key',                  // Required
    'baseUrl'       => 'https://api.darkstrata.io/v1/', // Optional
    'timeout'       => 30,                              // Optional, seconds (float allowed)
    'retries'       => 3,                               // Optional, retry attempts for retryable errors
    'enableCaching' => true,                            // Optional
    'cacheTtl'      => 3600,                            // Optional, seconds
    'prefixLength'  => 5,                               // Optional, 5 or 6 (see below)
]);

$result = $client->check('[email protected]', 'password123');

$hash = Crypto::hashCredential('[email protected]', 'password123');
$result = $client->checkHash($hash);

$results = $client->checkBatch([
    ['email' => '[email protected]', 'password' => 'alice123'],
    ['email' => '[email protected]', 'password' => 'bob456'],
]);

foreach ($results as $result) {
    echo $result->email, ': ', $result->found ? 'COMPROMISED' : 'Safe', "\n";
}

$hashes = array_map(fn($c) => Crypto::hashCredential($c['email'], $c['password']), $credentials);
$results = $client->checkHashBatch($hashes);

$size = $client->getCacheSize();
$client->clearCache();

$result = $client->check($email, $password, [
    'clientHmac' => 'your-64-char-hex-key...',
    'since' => new DateTimeImmutable('2023-01-01'),
]);

use DarkStrata\CredentialCheck\Exception\ApiException;
use DarkStrata\CredentialCheck\Exception\AuthenticationException;
use DarkStrata\CredentialCheck\Exception\DarkStrataException;
use DarkStrata\CredentialCheck\Exception\NetworkException;
use DarkStrata\CredentialCheck\Exception\RateLimitException;
use DarkStrata\CredentialCheck\Exception\TimeoutException;
use DarkStrata\CredentialCheck\Exception\ValidationException;

try {
    $result = $client->checkHash($hash);
} catch (AuthenticationException $e) {
    // 401 - invalid API key (not retryable)
} catch (ValidationException $e) {
    // Invalid input, see $e->getField()
} catch (RateLimitException $e) {
    // 429 - see $e->getRetryAfter() seconds
} catch (TimeoutException $e) {
    // Request timed out (retryable)
} catch (NetworkException $e) {
    // Connection failure (retryable)
} catch (ApiException $e) {
    // Other API error, see $e->getStatusCode() and $e->getResponseBody()
} catch (DarkStrataException $e) {
    // Anything else from the SDK
    if ($e->isRetryable()) {
        // Safe to try again later
    }
}

// SHA-256 of "email:password" with the email trimmed and lowercased
$hash = Crypto::hashCredential($email, $password);

// Plain SHA-256
$hash = Crypto::sha256($input);

// HMAC-SHA256 with a hex-encoded key
$hmac = Crypto::hmacSha256($message, $hexKey);

// k-anonymity prefix (5 chars by default, pass 6 for a smaller response)
$prefix = Crypto::extractPrefix($hash);

// Validation
Crypto::isValidHash($hash);     // 64 hex chars
Crypto::isValidPrefix($prefix); // 5 or 6 hex chars

$hash = Crypto::hashCredential($email, $password);
// ...store $hash securely...
$result = $client->checkHash($hash);

use DarkStrata\CredentialCheck\Laravel\NotCompromisedCredential;

// Registration or reset: the email is read from the same request
$request->validate([
    'email' => ['tly
$request->validate([
    'password' => ['

use DarkStrata\CredentialCheck\Laravel\CompromisedCredentialException;

try {
    Auth::attempt($credentials);
} catch (CompromisedCredentialException $e) {
    return redirect()->route('password.request')->with('status', $e->errors()['email'][0]);
}

use DarkStrata\CredentialCheck\Laravel\CompromisedCredentialDetected;

Event::listen(CompromisedCredentialDetected::class, function (CompromisedCredentialDetected $event) {
    // $event->source: 'login' or 'password'
    // $event->email, $event->userId
    // e.g. notify the security team, force a reset, lock the account
});
bash
php artisan darkstrata:check
bash
php artisan vendor:publish --tag=darkstrata-config
bash
composer install
composer test          # SDK, PHP 7.4+
composer test:laravel  # Laravel integration, PHP 8.2+