horsev / expiring-key-generator
Generate date-based expiring keys with SHA256 hashing and time-window validation
Package info
github.com/Horsev/expiring-key-generator-php
pkg:composer/horsev/expiring-key-generator
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^10
README
Generate date-based keys and validate them within a time window. Uses a secret alphabet for base-N encoding + SHA256 hashing.
PHP port of expiring-key-generator — keys are cross-compatible with the same secret.
- Zero dependencies (besides PHP 8.1+)
- Algorithmic generation
- No database needed
Install
composer require horsev/expiring-key-generator
Usage
<?php use Horsev\ExpiringKeyGenerator\ExpiringKeyGenerator; // 1. Generate a secret key (store this securely) $secretKey = ExpiringKeyGenerator::generateSecretKey(); // 2. Daily keys — generate and validate within N days $generateKey = ExpiringKeyGenerator::createKeyGenerator($secretKey); $key = $generateKey(new DateTime()); $isKeyValid = ExpiringKeyGenerator::createKeyValidator($secretKey); $isKeyValid($key, new DateTime(), 28); // true // 3. Hourly keys — generate and validate within N hours (1–24) $generateHourlyKey = ExpiringKeyGenerator::createHourlyKeyGenerator($secretKey); $hourlyKey = $generateHourlyKey(new DateTime()); $isHourlyKeyValid = ExpiringKeyGenerator::createHourlyKeyValidator($secretKey); $isHourlyKeyValid($hourlyKey, new DateTime(), 5); // true
API
generateSecretKey(): string
Returns a randomly shuffled 34-character string from a safe alphabet (A-Z without O, 1-9 without 0).
createKeyGenerator(string $secretKey): Closure
Throws if $secretKey is not a valid 34-character permutation of the safe alphabet.
Returns fn(DateTimeInterface $date): string that encodes a date into a deterministic base64 SHA256 hash.
createKeyValidator(string $secretKey): Closure
Throws if $secretKey is invalid.
Returns fn(string $hash, DateTimeInterface $currentDate, int $days): bool that checks whether a key was generated within the last $days days.
createHourlyKeyGenerator(string $secretKey): Closure
Returns fn(DateTimeInterface $date): string that encodes date+hour into a hash. Uses YYYYMMDDHH (10 digits).
createHourlyKeyValidator(string $secretKey): Closure
Returns fn(string $hash, DateTimeInterface $currentDate, int $hours): bool for 1–24 hour windows.
License
MIT