PHP code example of altcha-org / altcha

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

    

altcha-org / altcha example snippets




ltchaOrg\Altcha\Altcha;
use AltchaOrg\Altcha\CreateChallengeOptions;
use AltchaOrg\Altcha\SolveChallengeOptions;
use AltchaOrg\Altcha\VerifySolutionOptions;
use AltchaOrg\Altcha\Payload;
use AltchaOrg\Altcha\Algorithm\Pbkdf2;

$pbkdf2 = new Pbkdf2();
$altcha = new Altcha(
    hmacSignatureSecret: 'secret',
    hmacKeySignatureSecret: 'key-secret', // optional, enables fast verification path
);

// Create a new challenge
// Modify the cost and counter depending on the algorithm
$challenge = $altcha->createChallenge(new CreateChallengeOptions(
    algorithm: $pbkdf2,
    cost: 5000,
    counter: random_int(5000, 10000),
    expiresAt: time() + 600,
));

// Solve the challenge (client-side in production)
$solution = $altcha->solveChallenge(new SolveChallengeOptions(
    algorithm: $pbkdf2,
    challenge: $challenge,
));

// Verify the solution (server-side)
if ($solution !== null) {
    $payload = new Payload($challenge, $solution);
    $result = $altcha->verifySolution(new VerifySolutionOptions(
        algorithm: $pbkdf2,
        payload: $payload,
    ));

    if ($result->verified) {
        echo "Solution verified!\n";
    }
}

$altcha = new Altcha(
    hmacSignatureSecret: 'secret',
    hmacKeySignatureSecret: 'key-secret', // enables fast verification path
    hmacAlgorithm: HmacAlgorithm::SHA256, // default
);

use AltchaOrg\Altcha\Algorithm\Pbkdf2;
use AltchaOrg\Altcha\HmacAlgorithm;

new Pbkdf2();                        // PBKDF2/SHA-256
new Pbkdf2(HmacAlgorithm::SHA384);  // PBKDF2/SHA-384
new Pbkdf2(HmacAlgorithm::SHA512);  // PBKDF2/SHA-512

use AltchaOrg\Altcha\Algorithm\Argon2id;

new Argon2id();

use AltchaOrg\Altcha\Algorithm\Scrypt;

new Scrypt();

use AltchaOrg\Altcha\ServerSignature;

$result = ServerSignature::verifyServerSignature($payload, 'server-secret');

if ($result->verified) {
    $result->verificationData->expire;          // int
    $result->verificationData->score;           // float
    $result->verificationData->verified;        // bool
    $result->verificationData->fields;          // array
    $result->verificationData->classification;  // string
    $result->verificationData['email'];         // array access also works
}

$isValid = ServerSignature::verifyFieldsHash(
    formData: ['name' => 'John', 'email' => '[email protected]'],
    fields: ['name', 'email'],
    fieldsHash: hash('sha256', "John\[email protected]"),
);

$payload = new Payload($challenge, $solution);

$payload->toArray();   // array
$payload->toJson();    // JSON string
$payload->toBase64();  // base64-encoded JSON