Obfuscate your data by generating reversible, non-sequential, URL-safe identifiers.

Overview

Laravel Hashid

Latest Version on Packagist Software License Build Status StyleCI SensioLabsInsight Quality Score Code Coverage Total Downloads

Laravel Hashid provides a unified API across various drivers such as Base62, Base64, Hashids and Optimus, with support for multiple connections or different encoding options. It offers a simple, elegant way to obfuscate your data by generating reversible, non-sequential, URL-safe identifiers.

Installation

You can install this package using the Composer manager:

$ composer require elfsundae/laravel-hashid

For Lumen or earlier Laravel than v5.5, you need to register the service provider manually:

ElfSundae\Laravel\Hashid\HashidServiceProvider::class

Then publish the configuration file:

# For Laravel application:
$ php artisan vendor:publish --tag=hashid

# For Lumen application:
$ cp vendor/elfsundae/laravel-hashid/config/hashid.php config/hashid.php

Configuration

Our well documented configuration file is extremely similar to the configurations of numerous Laravel manager integrations such as Database, Queue, Cache and Filesystem. So you do not need to spend extra time to learn how to configure Hashid.

Additionally, for simplicity you do not need to add singleton drivers like Base64 to your config file as they have no encoding options, unless you would like to specify a meaningful connection name.

Let's see an example of the configuration:

'default' => 'id',

'connections' => [

    'basic' => [
        'driver' => 'base64',
    ],

    'hashids' => [
        'driver' => 'hashids',
        'salt' => 'sweet girl',
    ],

    'id' => [
        'driver' => 'hashids_integer',
        'salt' => 'My Application',
        'min_length' => 6,
        'alphabet' => '1234567890abcdef',
    ],

    'base62' => [
        'driver' => 'base62',
        'characters' => 'f9FkqDbzmn0QRru7PBVeGl5pU28LgIvYwSydK41sCO3htaicjZoWAJNxH6EMTX',
    ],

],

Usage

The hashid() helper or the Hashid facade may be used to interact with any of your configured connections or drivers:

use ElfSundae\Laravel\Hashid\Facades\Hashid;

// Obtain the default connection instance
hashid();
Hashid::connection();

// Obtain the "base62" connection instance
hashid('base62');
Hashid::connection('base62');

// Obtain the Base64 driver instance
hashid('base64');
Hashid::connection('base64');
Hashid::driver('base64');

There are only two methods you need to know to use any connection or driver:

  • encode($data) for encoding data.
  • decode($data) for decoding data.
hashid()->encode(123456);

hashid('base64')->decode('TGFyYXZlbA');

Hashid::encode(123456);

Hashid::connection('hashids')->decode('X68fkp');

And there are also two corresponding helper functions:

  • hashid_encode($data, $name = null)
  • hashid_decode($data, $name = null)
hashid_encode(123456);

hashid_decode('TGFyYXZlbA', 'base64');

Built-in Drivers

Base62

  • Drivers: base62 , base62_integer
  • Configuration:
    • characters : 62 unique characters
  • Backend: tuupola/base62
  • Notes:
    • You may use the hashid:alphabet command to generate random characters.
    • GMP is strongly recommended as it is much faster than pure PHP.

Base64

Hashids

  • Drivers: hashids , hashids_hex , hashids_integer , hashids_string
  • Configuration:
    • salt
    • min_length
    • alphabet : At least 16 unique characters
  • Backend: hashids/hashids
  • Notes:
    • You may use the hashid:alphabet command to generate a random alphabet.
    • GMP is strongly recommended.

Hex

  • Drivers: hex , hex_integer

Optimus

  • Drivers: optimus
  • Configuration:
    • prime : Large prime number lower than 2147483647
    • inverse : The inverse prime so that (PRIME * INVERSE) & MAXID == 1
    • random : A large random integer lower than 2147483647
  • Backend: jenssegers/optimus
  • Notes:
    • You may use the hashid:optimus command to generate needed numbers.
    • Only for integer numbers.
    • The max number can be handled correctly is 2147483647.

Custom Drivers

To create a custom Hashid driver, you only need to implement the ElfSundae\Laravel\Hashid\DriverInterface interface that contains two methods: encode and decode. The constructor can optionally receive the driver configuration from a $config argument, and type-hinted dependencies injection is supported as well:

<?php

namespace App\Hashid;

use ElfSundae\Laravel\Hashid\DriverInterface;
use Illuminate\Contracts\Encryption\Encrypter;

class CustomDriver implements DriverInterface
{
    protected $encrypter;

    protected $serialize;

    public function __construct(Encrypter $encrypter, array $config = [])
    {
        $this->encrypter = $encrypter;

        $this->serialize = $config['serialize'] ?? false;
    }

    public function encode($data)
    {
        return $this->encrypter->encrypt($data, $this->serialize);
    }

    public function decode($data)
    {
        return $this->encrypter->decrypt($data, $this->serialize);
    }
}

Now you can configure the connection with this driver:

'connections' => [

    'custom' => [
        'driver' => App\Hashid\CustomDriver::class,
        'serialize' => false,
    ],

    // ...
]

If you prefer a short name for your driver, just register a container binding with hashid.driver. prefix:

$this->app->bind('hashid.driver.custom', CustomDriver::class);

Testing

$ composer test

License

This package is open-sourced software licensed under the MIT License.

Comments
  • Laravel 8.0 Support

    Laravel 8.0 Support

    Hi;

    I tried to upgrade to Laravel 8 today but noticed your package does not support this in the composer.json.

    Is this something you'd like a PR for or are you happy to update the composer and tag a new release?

    Cheers

    Shaun

    opened by craftyshaun 2
  • hashid:optimus output as .env format

    hashid:optimus output as .env format

    hashid:optimus now output as a table. User need to manually copy each number and put it into configuration files. If it output as the same format as .env will allow user to just copy-paste whole contents.

    opened by ghost 1
  • Drop support for PHP 5.x, update hashids dependency to 3.x

    Drop support for PHP 5.x, update hashids dependency to 3.x

    Considering that PHP 7.x is required since quite some time in Laravel, I think it is safe and sane to drop 5.x support.

    This would allow to move on with some other dependencies such as hashids 3.x which requires PHP 7.x

    opened by vpratfr 1
  • The class Laravel\Lumen\Application does not exist. Did you forget a USE statement, or did you not list all dependencies?

    The class Laravel\Lumen\Application does not exist. Did you forget a USE statement, or did you not list all dependencies?

    see https://scrutinizer-ci.com/g/ElfSundae/laravel-hashid/issues/master/files/src/HashidServiceProvider.php?orderField=path&order=asc&honorSelectedPaths=0&issueId=24062700#inspectioncomment-89250941

    opened by ElfSundae 0
  • option() may return array

    option() may return array

    It seems like $this->option('characters') targeting Illuminate\Console\Command::option() can also be of type array; however, ElfSundae\Laravel\Hashid...enerateRandomAlphabet() does only seem to accept string, maybe add an additional type check?

    see https://scrutinizer-ci.com/g/ElfSundae/laravel-hashid/inspections/77523947-fb53-423e-bed4-490ff611ea6e/issues/files/src/Console/AlphabetGenerateCommand.php?status=new&orderField=path&order=asc&honorSelectedPaths=0&issueId=23996809#inspectioncomment-89146709

    opened by ElfSundae 0
  • [Insight] Usage of a function in loops should be avoided - in src/Console/AlphabetGenerateCommand.php, line 31

    [Insight] Usage of a function in loops should be avoided - in src/Console/AlphabetGenerateCommand.php, line 31

    in src/Console/AlphabetGenerateCommand.php, line 31

    This loop uses a function. To avoid the overhead of executing the function n times, you should precalculate it before the loop.

         *
         * @return mixed
         */
        public function handle()
        {
            for ($i = 0; $i < $this->getTimes(); $i++) {
                $this->comment(
                    $this->generateRandomAlphabet($this->option('characters'))
                );
            }
        }
    

    Posted from SensioLabsInsight

    opened by ElfSundae 0
  • Eloquent support

    Eloquent support

    I would like to create a pull request to add these traits for eloquent models. I would change it a bit to use this lib instead of hashid directly, but you get the idea.

    I use these two alot and think it would be great to include them to this lib

    HashID.php

    /**
     * Trait HashID
     * @package App\Traits
     * @property-read string $hash_id
     * @mixin Model
     */
    trait HashID
    {
        public function getHashIdAttribute()
        {
            return static::idToHash($this->getKey());
        }
    
        public static function idToHash($id)
        {
            return static::newHashId()->encode($id);
        }
    
        public static function hashToId($code)
        {
            $ids = static::newHashId()->decode($code);
            $id = empty($ids) ? null : $ids[0];
            return $id;
        }
    
        /**
         * @param $code
         * @param array $columns
         * @return static
         */
        public static function findByHash($code, $columns = null)
        {
            $id = static::hashToId($code);
            return static::find($id, $columns);
        }
    
        /**
         * @param $code
         * @param array $columns
         * @return static
         */
        public static function findOrFailByHash($code, $columns = null)
        {
            $id = static::hashToId($code);
            return static::findOrFail($id, $columns);
        }
    
        public static function newHashId()
        {
            return new Hashids(config('app.key'), 5, 'qwertyuiopasdfghjklzxcvbnm7894561230');
        }
    }
    
    

    HashIDRoutable.php

    
    /**
     * Trait HashID
     * @package App\Traits
     * @mixin \Eloquent
     * @mixin HashID
     */
    trait HashIDRoutable
    {
        public function getRouteKeyName()
        {
            return 'hash_id';
        }
    
        public function resolveRouteBinding($value)
        {
            return (new static)->find(static::hashToId($value));
        }
    }
    

    Usage

    
    class OrderReturn extends Model
    {
        use HashID; 
        use HashIDRoutable; // hash id is used instead of id
    }
    
    opened by AidasK 5
Owner
Elf Sundae
原谅我这一生不羁放纵爱自由。
Elf Sundae
HTML sanitizer, written in PHP, aiming to provide XSS-safe markup based on explicitly allowed tags, attributes and values.

TYPO3 HTML Sanitizer ℹ️ Common safe HTML tags & attributes as given in \TYPO3\HtmlSanitizer\Builder\CommonBuilder still might be adjusted, extended or

TYPO3 GitHub Department 18 Jul 18, 2022
A library for generating random numbers and strings

RandomLib A library for generating random numbers and strings of various strengths. This library is useful in security contexts. Install Via Composer

Anthony Ferrara 832 Nov 24, 2022
Security CSRF (cross-site request forgery) component provides a class CsrfTokenManager for generating and validating CSRF tokens.

Security Component - CSRF The Security CSRF (cross-site request forgery) component provides a class CsrfTokenManager for generating and validating CSR

Symfony 1.5k Jan 3, 2023
A simple PHP web backdoor allows you to retrieve directory/file contents and upload file(s) from the local machine or remote URL.

Simple PHP Web Backdoor A simple PHP web backdoor allows you to retrieve directory/file contents and upload file(s) from the local machine or remote U

Aqhmal Hafizi 15 Oct 7, 2022
API in PHP for DDoS Attacks (sends a command to a SSH Server from a URL)

SSH-PHP-API API in PHP for DDoS Attacks (sends a command to a SSH Server from a URL) [Install on Ubuntu 20.04: apt install apache2 php php-fpm php-ssh

Вентокс 3 Sep 23, 2022
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Jan 6, 2023
A minimalist, open source online pastebin where the server has zero knowledge of pasted data. Data is encrypted/decrypted in the browser using 256 bits AES.

Current version: 1.3.5 PrivateBin is a minimalist, open source online pastebin where the server has zero knowledge of pasted data. Data is encrypted a

null 4.6k Jan 7, 2023
Automatic Encrypt and Decrypt your database data. Tested and used on Laravel 8

Laravel Encrypt Database Automatic Encrypt and Decrypt your database data. Tested and used on Laravel 8. I'm yet building the tests. Important Note th

Wellington Barbosa 2 Dec 15, 2021
A simple php (lumen) app for sharing sensitive text (basically like onetimesecret), but with full end-to-end AES-256-GCM encryption so even the server has no access to the data, and developed with very simple deployment in mind.

A simple php (lumen) app for sharing sensitive text (basically like onetimesecret), but with full end-to-end AES-256-GCM encryption so even the server has no access to the data, and developed with very simple deployment in mind.

Alan Woo 51 Nov 21, 2022
Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication.

Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication. PGP is used for signing, encrypting, and decrypting texts, e-mails, files, directories, and whole disk partitions and to increase the security of e-mail communications. Phil Zimmermann developed PGP in 1991.

[sCRiPTz-TEAM] 3 Dec 31, 2021
HTML/PHP/CSS website that tracks two API data

Detailed instructions on how to build and run Step 1: download XAMPP for a live web server XAMPP download 1 XAMP download 2 Step 2: Download all files

Winsor Tse 0 Jun 2, 2022
Easily anonymize sensitive data through eloquent queries

Laravel Encryptable This package allows you to anonymize sensitive data (like the name, surname and email address of a user) similarly to Laravel's En

H-FARM Innovation 93 Sep 6, 2022
Run locally to export crypto tx data from crypto exchanges using their api connections, and process into a normalised format.

CryptoCredible The missing crypto-exchange data exporter tldr: run locally to export your crypto tx data from popular exchanges via api connections. E

Lee Overy 6 Apr 6, 2022
🔒 Password Exposed Helper Function - Check if a password has been exposed in a data breach.

?? Password Exposed Helper Function This PHP package provides a password_exposed helper function, that uses the haveibeenpwned.com API to check if a p

Jordan Hall 212 Oct 24, 2022
Fides provides your servers with a trusted CA certificate, and signs your OpenSSH certificates with the same key

Fides is an SSH certificate signing server. It enables zero-trust infrastructure for your engineers by dynamically, and transparently, issuing short-lived certificates with clearly defined permissions.

Moritz Friedrich 3 Dec 28, 2022
PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application

PHPIDS PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web ap

null 752 Jan 3, 2023
SyCaptchaBundle is a form protection bundle made for Symfony, including a set of CAPTCHA challenges that should stop any malicious requests from submitting your forms.

SyCaptchaBundle is a form protection bundle made for Symfony, including a set of CAPTCHA challenges that should stop any malicious requests from submitting your forms.

Matt 1 Oct 4, 2022
Protect your server from griefer

A Simple anti grief PocketMine-MP Plugin

Azel F. 2 Mar 1, 2022