Laravel 5.4按会话ID加密

时间:2017-07-19 12:46:34

标签: php laravel laravel-5.4

我正在寻找使用会话ID加密文件ID的方法,并将其用作临时网址进行下载。

我在Laravel中找到了encrypt函数,但这并不是我想要的。是否有一些类似的函数可以使用会话ID字符串进行编码和解码?

1 个答案:

答案 0 :(得分:0)

make function in 
**Path -  /app/Libraries/Scramble.php**

**<Scramble.php>**
<?php

namespace App\Libraries;

use Crypt;
use Session;
use Illuminate\Contracts\Encryption\EncryptException;

class Scramble
{

    public function __construct()
    {
    }

    /**
     * Encrypt the given value with session binding.
     *
     * @param string $value
     *
     * @return string
     *
     * @throws \Illuminate\Contracts\Encryption\EncryptException
     */
    public static function encrypt($value)
    {
        if ($value === false) {
            throw new EncryptException('Could not encrypt the data.');
        }
        $manupulate_val = Session::getId()."##".config('app.key')."##".$value;
        return Crypt::encrypt($manupulate_val);
    }

    /**
     * Decrypt the given value.
     *
     * @param  string  $decrypted
     * @return string
     *
     * @throws \Illuminate\Contracts\Encryption\DecryptException
     */
    public static function decrypt($decrypted)
    {
        if ($decrypted === false) {
            throw new DecryptException('Could not decrypt the data.');
        }

        $sess_id         = Session::getId();
        $decryptedStr    = Crypt::decrypt($decrypted);
        $decryptedStrArr = explode("##", $decryptedStr);

        if (is_array($decryptedStrArr) && $decryptedStrArr['0'] !== $sess_id) {
            abort(400);
        }

        if (is_array($decryptedStrArr) && $decryptedStrArr['1'] !== config('app.key')) {
            abort(400);
        }

        return $decryptedStrArr['2'];
    }
}
**</scramble.php>**

now you can call anywhere....

use App\Libraries\Scramble;

$Yourid = 12345;
$sessionIdWithencData = Scramble::encrypt($Yourid);
$sessionIdWithdecData = Scramble::decrypt($sessionIdWithencData);
dd($sessionIdWithdecData);
==========================================


i hope this is help full