Skip to content

Instantly share code, notes, and snippets.

@Bo0oM
Created May 15, 2020 08:01
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Bo0oM/4705db359799c3871a810cd3f22dd1e6 to your computer and use it in GitHub Desktop.
Save Bo0oM/4705db359799c3871a810cd3f22dd1e6 to your computer and use it in GitHub Desktop.
Laravel Encryptor
<?php
class LaravelEncryptor {
private $key;
private $cipher;
public function __construct($key = 'ABCDEF1234567890ABCDEF1234567890', $cipher = 'AES-256-CBC') {
$this->key = substr($key, 0, 7) == 'base64:' ? base64_decode(substr($key, 7)) : $key;
$this->cipher = $cipher;
}
public function encrypt($value, $serialize = false) {
$iv = random_bytes(openssl_cipher_iv_length($this->cipher));
$value = openssl_encrypt(
$serialize ? serialize($value) : $value,
$this->cipher, $this->key, 0, $iv
);
$iv = base64_encode($iv);
$mac = hash_hmac('sha256', $iv . $value, $this->key);
$json = json_encode(compact('iv', 'value', 'mac'));
return base64_encode($json);
}
public function decrypt($payload, $unserialize = false) {
$payload = json_decode(base64_decode($payload), true);
$iv = base64_decode($payload['iv']);
$decrypted = openssl_decrypt(
$payload['value'], $this->cipher, $this->key, 0, $iv
);
return $unserialize ? unserialize($decrypted) : $decrypted;
}
}
$app_key = 'ABCDEF1234567890ABCDEF1234567890'; // .env
$app_name = 'Laravel'; // .env
$session_key = 'is_admin';
$session_value = true;
$session_id = 'AgCojIZgnHelIPpGA4KfLZns8hY7ctb5lm2T2CHj'; // storage/framework/sessions/
$csrftoken = 'xxx'; // if u need it
// SESSION_DRIVER=cookie
$session = [
'data' => serialize([
'_token' => $csrftoken,
$session_key => $session_value,
'_previous' => ['url' => 'http://localhost/'],
'_flash' => [
'old' => [],
'new' => [],
],
]),
'expires' => time() + 86400,
];
$enc = new LaravelEncryptor($app_key);
$encrypted_session = $enc->encrypt(json_encode($session), true);
$encrypted_csrftoken = $enc->encrypt($csrftoken, true);
$encrypted_session_id = $enc->encrypt($session_id, true);
echo 'Cookie: XSRF-TOKEN=' . urlencode($encrypted_csrftoken) . '; ' . $app_name . '_session=' . urlencode($encrypted_session_id) . '; ' . $session_id . '=' . urlencode($encrypted_session);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment