altcha-org/altcha

v0.1.2 2024-07-28 14:39 UTC

This package is auto-updated.

Last update: 2024-09-22 11:33:07 UTC


README

ALTCHA PHP 库是一个轻量级、无依赖库,专为创建和验证 ALTCHA 挑战而设计,特别适用于 PHP 应用程序。

兼容性

此库与以下兼容

  • PHP 7.4+
  • 所有主流平台(Linux、Windows、macOS)

示例

安装

要安装 ALTCHA PHP 库,请使用以下命令

composer require altcha-org/altcha

用法

以下是一个使用 ALTCHA PHP 库的基本示例

<?php

require 'vendor/autoload.php';

use AltchaOrg\Altcha\ChallengeOptions;
use AltchaOrg\Altcha\Altcha;

$hmacKey = 'secret hmac key';

// Create a new challenge
$options = new ChallengeOptions([
    'hmacKey'   => $hmacKey,
    'maxNumber' => 50000, // the maximum random number
]);

$challenge = Altcha::createChallenge($options);
echo "Challenge created: " . json_encode($challenge) . "\n";

// Example payload to verify
$payload = [
    'algorithm' => $challenge->algorithm,
    'challenge' => $challenge->challenge,
    'number'    => 12345, // Example number
    'salt'      => $challenge->salt,
    'signature' => $challenge->signature,
];

// Verify the solution
$ok = Altcha::verifySolution($payload, $hmacKey, true);

if ($ok) {
    echo "Solution verified!\n";
} else {
    echo "Invalid solution.\n";
}

API

Altcha::createChallenge(array $options): array

为 ALTCHA 创建一个新的挑战。

参数

  • options 数组:
    • algorithm string: 要使用的哈希算法 (SHA-1, SHA-256, SHA-512, 默认: SHA-256)。
    • maxNumber int: 随机数生成器的最大数字 (默认: 1,000,000)。
    • saltLength int: 随机盐的长度 (默认: 12 字节)。
    • hmacKey string: 所需的 HMAC 密钥。
    • salt string: 可选的盐字符串。如果不提供,将生成随机盐。
    • number int: 可选的特定数字。如果不提供,将生成随机数字。
    • expires \DateTime: 可选的挑战过期时间。
    • params array: 可选的 URL 编码查询参数。

返回: array

Altcha::verifySolution(array $payload, string $hmacKey, bool $checkExpires): bool

验证 ALTCHA 解决方案。

参数

  • payload array: 要验证的解决方案有效负载。
  • hmacKey string: 用于验证的 HMAC 密钥。
  • checkExpires bool: 是否检查挑战是否已过期。

返回: bool

Altcha::extractParams(array $payload): array

从有效负载的盐中提取 URL 参数。

参数

  • payload array: 包含盐的有效负载。

返回: array

Altcha::verifyFieldsHash(array $formData, array $fields, string $fieldsHash, string $algorithm): bool

验证表单字段的哈希值。

参数

  • formData array: 要哈希的表单数据。
  • fields array: 要包含在哈希中的字段。
  • fieldsHash string: 预期的哈希值。
  • algorithm string: 哈希算法 (SHA-1, SHA-256, SHA-512)。

返回: bool

Altcha::verifyServerSignature($payload, string $hmacKey): array

验证服务器签名。

参数

  • payload mixed: 要验证的有效负载(字符串或 ServerSignaturePayload 数组)。
  • hmacKey string: 用于验证的 HMAC 密钥。

返回: array

Altcha::solveChallenge(string $challenge, string $salt, string $algorithm, int $max, int $start, $stopChan = null): array

找到给定挑战的解决方案。

参数

  • challenge string: 挑战的哈希。
  • salt string: 挑战的盐。
  • algorithm string: 哈希算法 (SHA-1, SHA-256, SHA-512)。
  • max int: 迭代到的最大数字。
  • start int: 开始数字。

返回: array

测试

vendor/bin/phpunit --bootstrap src/Altcha.php tests/AltchaTest.php

许可证

MIT