Download the PHP package digitaltunnel/secure-code without Composer
On this page you can find all versions of the php package digitaltunnel/secure-code. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package secure-code
Secure Code
Cryptographically secure random code generator with a fluent API for Laravel.
Generate PINs, voucher codes, serial keys, invite tokens, verification codes, sequential document IDs, and more -- all powered by PHP's random_int() CSPRNG under the hood.
Table of Contents
- Requirements
- Installation
- Quick Start
- Configuration
- Usage
- Basic Generation
- Code Length
- Character Sets
- Custom Character Pool
- Prefix & Suffix
- Separators
- Case Forcing
- Exclude Similar Characters
- Batch Generation
- Uniqueness Checking
- Database Uniqueness
- Max Attempts
- Presets
- Pattern-Based Generation
- Checksum (Luhn & Mod-97)
- Code Masking
- Entropy Calculator
- Code Vault (TTL & Verification)
- HashId Encoding
- Export (JSON, CSV, Text)
- Events
- Validation Rule
- Sequential Document IDs
- Artisan Command
- Blade Directive
- Facade
- Combining Options
- API Reference
- Real-World Examples
- Architecture
- Testing
- Security
- License
Requirements
| Dependency | Version |
|---|---|
| PHP | ^8.2 |
| Laravel | 11.x, 12.x, 13.x |
| ext-bcmath | * |
Installation
The package auto-discovers its service provider and facade. No manual registration needed.
Publish Configuration (optional)
This publishes config/secure-code.php where you can set application-wide defaults.
Publish Migrations (required for Sequential IDs)
This creates the secure_code_sequences table used by the sequential document ID generator. Only needed if you use the sequence() feature.
Quick Start
Configuration
After publishing, edit config/secure-code.php:
All options can be overridden per-call via the fluent API.
Usage
Basic Generation
Code Length
Character Sets
The Charset enum provides 13 predefined character pools:
Available Charsets:
| Charset | Characters | Pool Size |
|---|---|---|
Numeric |
0-9 |
10 |
Alpha |
A-Z a-z |
52 |
AlphaUpper |
A-Z |
26 |
AlphaLower |
a-z |
26 |
Alphanumeric |
0-9 A-Z a-z |
62 |
AlphanumericUpper |
0-9 A-Z |
36 |
AlphanumericLower |
0-9 a-z |
36 |
Hex |
0-9 a-f |
16 |
HexUpper |
0-9 A-F |
16 |
Binary |
0 1 |
2 |
Base32 |
A-Z 2-7 |
32 |
Base58 |
1-9 A-H J-N P-Z a-k m-z |
58 |
Base64Safe |
A-Z a-z 0-9 - _ |
64 |
Custom Character Pool
Prefix & Suffix
Prefix and suffix are not counted toward
length.
Separators
Separators are inserted after generation and don't affect the random character count.
Case Forcing
Exclude Similar Characters
Remove visually ambiguous characters (0, O, 1, I, l) from the pool:
Batch Generation
When count is 1, a single string is returned (not an array). Codes within a batch are always unique to each other.
Uniqueness Checking
Using a Closure:
Using the UniquenessChecker Interface:
Database Uniqueness
Built-in shorthand for database uniqueness -- no manual closure needed:
Max Attempts
Default: 1000 (configurable in config/secure-code.php).
Presets
Preconfigured templates for common use cases:
You can also use the enum directly and override options:
Available Presets:
| Preset | Length | Charset | Extras |
|---|---|---|---|
pin |
6 | Numeric | -- |
otp |
6 | Numeric | -- |
voucher |
16 | AlphanumericUpper | excludeSimilar, separator - every 4 |
serial |
20 | HexUpper | separator - every 4 |
api-key |
40 | Base64Safe | prefix sk_ |
token |
64 | Alphanumeric | -- |
invite |
12 | Base58 | -- |
Pattern-Based Generation
Define the exact shape of your code using placeholder characters:
| Placeholder | Produces |
|---|---|
A |
Uppercase letter (A-Z) |
a |
Lowercase letter (a-z) |
9 |
Digit (0-9) |
X |
Hex character (0-9, A-F) |
* |
Any alphanumeric |
| Anything else | Kept as literal |
Checksum (Luhn & Mod-97)
Append self-validating check digits to generated codes:
Luhn (for numeric codes):
Mod-97 (for alphanumeric codes):
Use directly:
Code Masking
Hide parts of a code for secure display in UIs and logs:
Entropy Calculator
Evaluate the security strength of your code configuration before generating:
Strength levels:
| Bits | Strength |
|---|---|
| < 28 | very weak |
| 28-47 | weak |
| 48-79 | moderate |
| 80-127 | strong |
| 128+ | very strong |
Code Vault (TTL & Verification)
Issue short-lived codes with automatic expiry and brute-force protection -- ideal for email verification, 2FA, and OTP flows:
The vault uses timing-safe comparison (hash_equals) and automatically deletes the code after max failed attempts to prevent brute-force attacks.
HashId Encoding
Encode integer IDs into short, obfuscated strings (reversible):
Export (JSON, CSV, Text)
Generate codes and export them directly:
Events
Opt-in event dispatching for audit logging:
Listen for events in your EventServiceProvider or with closures:
Events are not dispatched by default -- you must call withEvents() to opt in.
Validation Rule
Validate incoming codes against format, length, charset, pattern, or checksum:
Sequential Document IDs
Generate gap-free, duplicate-free sequential document numbers (invoices, orders, receipts, etc.) backed by database-level locking. Safe for heavy concurrent transactions.
Requires migration: Run
php artisan vendor:publish --tag=secure-code-migrations && php artisan migratefirst.
Basic usage:
Full format with date tokens:
Batch allocation (atomic, contiguous):
Inspect and preview:
Period-based reset:
Custom start value and DB connection:
Format tokens:
| Token | Example | Description |
|---|---|---|
{prefix} |
INV- |
Configured prefix |
{suffix} |
-EG |
Configured suffix |
{sequence} |
00001 |
Zero-padded sequence number |
{separator} |
- |
Configured separator |
{Y} |
2026 |
4-digit year |
{y} |
26 |
2-digit year |
{m} |
04 |
2-digit month |
{d} |
04 |
2-digit day |
{timestamp} |
1775433600 |
Unix timestamp |
How it works under the hood:
- Each call to
next()runs an autonomous database transaction withSELECT ... FOR UPDATE - This acquires an exclusive row lock, preventing concurrent access
- The sequence number is committed immediately, independent of any outer transaction
- No gaps: numbers are contiguous (1, 2, 3, ...)
- No duplicates: row-level locking serializes access
- Deadlock-free: each operation locks exactly one row
- Different sequence keys (
'invoice'vs'order') are fully independent
Tip: For strict isolation from your application's transactions, configure a dedicated database connection in
config/secure-code.phpundersequences.connection.
Artisan Command
Generate codes from the command line:
Blade Directive
Quick inline generation in Blade templates:
Facade
The package registers a facade automatically:
Combining Options
All methods are chainable and can be freely combined:
API Reference
SecureCode (Static Entry Point)
| Method | Returns | Description |
|---|---|---|
generate() |
string\|array |
Generate with default config |
length(int) |
CodeBuilder |
Set code length |
charset(Charset) |
CodeBuilder |
Set character set |
pool(string) |
CodeBuilder |
Set custom character pool |
prefix(string) |
CodeBuilder |
Set prefix |
suffix(string) |
CodeBuilder |
Set suffix |
separator(string, int) |
CodeBuilder |
Set separator and interval |
uppercase() |
CodeBuilder |
Force uppercase |
lowercase() |
CodeBuilder |
Force lowercase |
excludeSimilar(bool) |
CodeBuilder |
Exclude ambiguous characters |
count(int) |
CodeBuilder |
Set batch size |
unique(Closure\|UniquenessChecker) |
CodeBuilder |
Set uniqueness checker |
uniqueInTable(string, string, ?string) |
CodeBuilder |
Database uniqueness |
maxAttempts(int) |
CodeBuilder |
Set max retry attempts |
preset(string\|Preset) |
CodeBuilder |
Apply a preset |
pattern(string) |
CodeBuilder |
Set generation pattern |
withChecksum(string) |
CodeBuilder |
Append checksum digit |
withEvents(bool) |
CodeBuilder |
Enable event dispatching |
mask(string, ...) |
string |
Mask a code for display |
verifyChecksum(string, string) |
bool |
Verify a checksum |
vault(int, Charset, int, int) |
CodeVault |
Create a code vault |
hashid(string, int) |
HashId |
Create a HashId encoder |
sequence(string) |
SequenceBuilder |
Create a sequential ID builder |
CodeBuilder (Fluent Builder)
Immutable -- every method returns a new instance:
Additional methods on CodeBuilder:
| Method | Returns | Description |
|---|---|---|
toJson(bool $pretty) |
string |
Generate + export as JSON |
toCsv(string $header) |
string |
Generate + export as CSV |
toText() |
string |
Generate + export as text |
entropy() |
array |
Calculate entropy info |
Support Classes
| Class | Description |
|---|---|
Checksum::appendLuhn(string) |
Append Luhn check digit |
Checksum::verifyLuhn(string) |
Verify Luhn checksum |
Checksum::appendMod97(string) |
Append mod-97 check digits |
Checksum::verifyMod97(string) |
Verify mod-97 checksum |
Mask::apply(string, ...) |
Mask a code string |
Entropy::calculate(int, int) |
Calculate entropy bits |
Entropy::strength(float) |
Get strength label |
Export::toJson(array, bool) |
Export as JSON |
Export::toCsv(array, string) |
Export as CSV |
Export::toText(array) |
Export as plain text |
PatternGenerator::generate(string) |
Generate from pattern |
PatternGenerator::toRegex(string) |
Convert pattern to regex |
HashId::encode(int) |
Encode integer |
HashId::decode(string) |
Decode to integer |
SequenceBuilder (Fluent Builder)
Immutable -- every method returns a new instance:
| Method | Returns | Description |
|---|---|---|
prefix(string) |
SequenceBuilder |
Set ID prefix |
suffix(string) |
SequenceBuilder |
Set ID suffix |
separator(string) |
SequenceBuilder |
Set separator character |
format(string) |
SequenceBuilder |
Set format template with tokens |
padSequence(int) |
SequenceBuilder |
Set zero-pad width |
resetEvery(string\|SequenceResetPeriod) |
SequenceBuilder |
Set reset period |
startAt(int) |
SequenceBuilder |
Set initial sequence value |
connection(string) |
SequenceBuilder |
Set database connection |
date(DateTimeInterface) |
SequenceBuilder |
Set date for formatting and period key |
next(int $count = 1) |
string\|array |
Allocate and return next ID(s) |
current() |
?int |
Get last allocated value |
preview() |
string |
Preview next ID without allocating |
Real-World Examples
Email Verification Flow
Gift Card with Self-Validating Checksum
Obfuscated Order URLs
Batch Promo Codes Export
Security Audit with Entropy Check
Two-Factor Authentication
Invoice Numbers (Sequential)
Architecture
Security: All randomness is produced by random_int(), which draws from the OS CSPRNG. The Code Vault uses hash_equals for timing-safe comparison.
Immutability: CodeBuilder clones itself on every fluent call. Safe to store and reuse as templates.
Testing
The package ships with 171 Pest tests covering every feature:
Security
If you discover a security vulnerability, please send an email to [email protected] instead of opening a public issue.
See SECURITY.md for full details on our security policy, supported versions, and best practices.
License
The MIT License (MIT). See LICENSE for details.
All versions of secure-code with dependencies
ext-bcmath Version *
illuminate/database Version ^11.0|^12.0|^13.0
illuminate/support Version ^11.0|^12.0|^13.0