laravel5使用hashids对id进行加密

1,456 阅读2分钟

很多文章id都是有规律的,能爬接口的数据或者获取到本页面的内容

为了防止这种情况的事情发生,我们将使用hashids加密,来生成不规律的编号

这样就不会造成被人爬数据的情况了,下面我将演示详细的流程

laravel-hashids的github网址:https://github.com/vinkla/laravel-hashids

在laravel中安装hashids

composer require vinkla/hashids v3.3.0

PS:因为现在 vinkla/hashids最新版本支持5.7,我的laravel版本为5.5,所以要对应相应的版本号

在config/app.php中的providers数组中添加

Vinkla\Hashids\HashidsServiceProvider::class,

在config/app.php中的aliases数组中添加

'Hashids' => Vinkla\Hashids\Facades\Hashids::class,

config下生成hashids.php配置文件

php artisan vendor:publish

修改hashids.php中的connections的盐值和加密输出长度

其中盐值可以是任意长度任意字符的字符串,加密和盐值有直接的关系,盐值是解密的钥匙。我直接取项目的密钥作为其盐值,以让项目统一,且不同项目的加密结果不一样。

'connections' => [
    'main' => [
        'salt' => env('APP_KEY'),
        'length' => '6',
    ],

    'alternative' => [
        'salt' => 'your-salt-string',
        'length' => 'your-length-integer',
    ],
],

Hashids的加密解密使用方式

  • 加密的使用方式
Hashids::encode(123);//返回经过加密后的字符串o7gxkR
  • 解密的使用方式 注意返回值是数组
Hashids::decode('o7gxkR');//返回经过解密后的数组array(1) { [0]=> int(123456) }
  • 同时加密多个参数
Hashids::encode(1,2,3);//KPCAig
  • 解密多个参数的加密字符串
Hashids::decode('M0BKxg8cYSNrVAjp')//返回经过解密后的数组array(3){[0]=> int(1) [1]=> int(2) [2]=> int(3)}
  • 切换不同的盐值和加密长度
    我们可能需要对多个不同类型的id进行加密,盐值和返回长度也各有不同。所以config的hashids中的多个数组可以派上用场了。其中main数组是作为默认连接,可以自行添加其他的加密数组。
Hashids::connection('alternative')->encode(*);
Hashids::connection('alternative')->decode("**");

纯原创,所有作品都是实战经验,希望可以获得大家的支持。