ALTCHA PHP Library
A lightweight PHP library for creating and verifying ALTCHA challenges using key derivation functions (PBKDF2, Argon2id, Scrypt).
Compatibility
Migrating from V1 to V2
Example
Installation
composer require altcha-org/altcha
Usage
<?php
require 'vendor/autoload.php';
use AltchaOrg\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";
}
}
VerifySolutionOptions::$payload also accepts the raw base64-encoded string posted by the widget, or a decoded associative array — no manual parsing required:
// $_POST['altcha'] is the base64-encoded payload string from the widget
$result = $altcha->verifySolution(new VerifySolutionOptions(
payload: $_POST['altcha'],
algorithm: $pbkdf2,
));
API
Altcha
$altcha = new Altcha(
hmacSignatureSecret: 'secret',
hmacKeySignatureSecret: 'key-secret', // enables fast verification path
hmacAlgorithm: HmacAlgorithm::SHA256, // default
);
hmacSignatureSecret is required for verification: without it (or with ''), createChallenge returns unsigned challenges and verifySolution always fails with invalidSignature. Omit it only when creating/solving challenges you never verify (e.g. Obfuscator).
Altcha::createChallenge(CreateChallengeOptions $options): Challenge
Creates a new challenge.
CreateChallengeOptions
| Parameter |
Type |
Default |
Description |
algorithm |
DeriveKeyInterface |
required |
Key derivation algorithm |
cost |
int |
required |
Iterations/time cost |
counter |
?int |
null |
Counter for deterministic mode |
data |
?array |
null |
Custom metadata, a JSON object of scalar/null values (as in altcha-lib JS); signed in the same canonical form as JS. Strings must be valid UTF-8 (otherwise JsonException) |
expiresAt |
DateTimeInterface|int|float|null |
null |
Unix timestamp (seconds, fractional allowed) for expiration; 0 means no expiry |
keyLength |
int |
32 |
Derived key length in bytes |
keyPrefixLength |
int |
keyLength / 2 |
Key prefix length in bytes |
memoryCost |
?int |
null |
Memory cost (Argon2id/Scrypt) |
nonce |
?string |
null |
Custom nonce (hex) |
parallelism |
?int |
null |
Parallelism factor (Scrypt) |
salt |
?string |
null |
Custom salt (hex) |
When counter is provided and hmacKeySignatureSecret is set, the challenge includes a keySignature (HMAC of the raw derived key bytes, compatible with altcha-lib for JS) for fast verification. Verification then only checks the submitted key against keySignature and skips re-derivation; a mismatch fails as invalidSolution with no fallback.
Returns: Challenge with parameters (ChallengeParameters) and signature.
Altcha::solveChallenge(SolveChallengeOptions $options): ?Solution
Iterates counter values to find a derived key matching the challenge prefix.
SolveChallengeOptions
| Parameter |
Type |
Default |
Description |
algorithm |
DeriveKeyInterface |
required |
Key derivation algorithm |
challenge |
Challenge |
required |
The challenge to solve |
start |
int |
0 |
Initial counter value |
step |
int |
1 |
Counter increment per iteration |
timeout |
float |
30.0 |
Timeout in seconds |
Returns: Solution with counter, derivedKey (hex), and time (seconds). Returns null if no match is found.
Altcha::verifySolution(VerifySolutionOptions $options): VerifySolutionResult
Verifies a solution against its challenge.
VerifySolutionOptions
| Parameter |
Type |
Default |
Description |
algorithm |
DeriveKeyInterface |
required |
Key derivation algorithm |
payload |
Payload|string|array |
required |
Challenge + solution pair — a Payload object, a raw base64-encoded payload string (as posted by the widget), or a decoded associative array. Throws InvalidArgumentException if a string/array can't be parsed into a valid payload. |
VerifySolutionResult
| Property |
Type |
Description |
verified |
bool |
Whether the solution is valid |
expired |
bool |
Whether the challenge has expired |
invalidSignature |
?bool |
Whether the challenge signature is invalid |
invalidSolution |
?bool |
Whether the derived key doesn't match |
time |
float |
Verification time in seconds |
Key Derivation Algorithms
All algorithms implement DeriveKeyInterface.
PBKDF2
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
Argon2id
Requires ext-sodium (typically bundled with PHP).
use AltchaOrg\Altcha\Algorithm\Argon2id;
new Argon2id();
Uses memoryCost from challenge options.
Scrypt
Requires ext-scrypt (php-scrypt).
use AltchaOrg\Altcha\Algorithm\Scrypt;
new Scrypt();
Uses memoryCost (r, default: 8) and parallelism (p, default: 1) from challenge options.
HmacAlgorithm
Enum used for HMAC signing and PBKDF2 hash selection:
HmacAlgorithm::SHA256 - SHA-256
HmacAlgorithm::SHA384 - SHA-384
HmacAlgorithm::SHA512 - SHA-512
ServerSignature::verifyServerSignature(string|array $data, string $hmacKey, HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256): ServerSignatureVerification
Verifies a server signature payload.
ServerSignatureVerification
| Property |
Type |
Description |
verified |
bool |
Whether the signature is valid, not expired, and solution verified |
expired |
bool |
Whether the verification data has expired |
invalidSignature |
bool |
Whether the HMAC signature is invalid |
invalidSolution |
bool |
Whether the solution was not verified |
time |
float |
Verification time in seconds |
verificationData |
?ServerSignatureVerificationData |
Parsed verification data |
Verification data is parsed generically from URL-encoded params with auto-detected types (bool, int, float, string, array for fields/reasons). Access values via property or array syntax:
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
}
ServerSignature::verifyFieldsHash(array $formData, array $fields, string $fieldsHash, HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256): bool
Verifies the hash of specific form fields.
$isValid = ServerSignature::verifyFieldsHash(
formData: ['name' => 'John', 'email' => 'john@example.com'],
fields: ['name', 'email'],
fieldsHash: hash('sha256', "John\njohn@example.com"),
);
Sentinel::verify(VerifyServerOptions $options): VerifyServerResult
Verifies a payload remotely by calling ALTCHA Sentinel's verify signature API, instead of verifying the HMAC signature locally. Useful when Sentinel issues and signs challenges directly, so your server doesn't need to hold the HMAC secret at all. Both Sentinel v2 (POST /v2/verify/signature) and Sentinel v1 (POST /v1/verify/signature) are supported; they differ in how the request is authenticated.
Sentinel v2
use AltchaOrg\Altcha\Sentinel;
use AltchaOrg\Altcha\VerifyServerApiKey;
use AltchaOrg\Altcha\VerifyServerOptions;
$result = Sentinel::verify(new VerifyServerOptions(
payload: $_POST['altcha'], // raw base64 string from POST /v2/verify, or a decoded array
url: 'https://sentinel.example.com/v2/verify/signature',
apiKey: new VerifyServerApiKey($sentinelApiKeyId, $sentinelApiKeySecret), // restricted or full key
timeout: 10.0,
retries: 2,
));
if ($result->verified) {
// ...
}
apiKey is a restricted or full API key of the account that owns the payload's (public) API key. It is sent as Authorization: Basic base64(id:secret). Sentinel v2 rejects unauthenticated requests to /v2/verify/signature (API_KEY_REQUIRED).
- The request body is
{"payload": …}. secret is not sent when apiKey is set.
- Sentinel v2 returns
verificationData nested ({"device": {"browser": …}}). Sentinel::verify flattens it to the signed dotted keys ($result->verificationData['device.browser']); lists such as fields and reasons stay arrays.
Sentinel v1
use AltchaOrg\Altcha\Sentinel;
use AltchaOrg\Altcha\VerifyServerOptions;
$result = Sentinel::verify(new VerifyServerOptions(
payload: $_POST['altcha'], // raw base64 string from POST /v1/verify, or a decoded array
url: 'https://sentinel.example.com/v1/verify/signature',
secret: $sentinelApiKeySecret, // optional, checked against the payload's API key
timeout: 10.0,
retries: 2,
));
if ($result->verified) {
// ...
}
/v1/verify/signature takes no credentials. secret (the API key secret) is optional and is sent in the request body as {"payload": …, "secret": …}; Sentinel answers WRONG_API_KEY_SECRET when it is not the payload key's secret.
- This also applies to the
/v1/verify/signature alias Sentinel v2 serves with [server] v1_compat = true.
VerifyServerOptions
| Parameter |
Type |
Default |
Description |
payload |
string|array |
required |
The payload to verify, as received from the client (raw base64 string or decoded array) |
url |
string |
required |
Full URL of the Sentinel endpoint: /v2/verify/signature (v2) or /v1/verify/signature (v1) |
secret |
?string |
null |
Sentinel v1 only: API key secret sent in the body and checked against the payload's API key. Ignored when apiKey is set |