Skip to content

Instantly share code, notes, and snippets.

@akhileshdarjee
Last active April 13, 2022 13:03
Show Gist options
  • Save akhileshdarjee/27b49925609ff86b5319ccd9ea83a6e1 to your computer and use it in GitHub Desktop.
Save akhileshdarjee/27b49925609ff86b5319ccd9ea83a6e1 to your computer and use it in GitHub Desktop.
Laravel Encrypt & Decrypt string
<?php
# Laravel provides a convenient way to encrypt/decrypt a string i.e. encrypt() and decrypt() methods, but the output string is too long.
# It also provides a bcrypt() method where the output string is not lengthy but is not URL friendly.
# Here's a function to encrypt/decrypt a string, which is also URL friendly and the encrypted string length is way small:
/**
* Encrypt & decrypt strings.
*
* Create secret key & iv bu running the following commands
* $secret_key = echo base64_encode(openssl_random_pseudo_bytes(32));
* $secret_iv = echo base64_encode(openssl_random_pseudo_bytes(64));
*
* @param string $string
* @param string $action
*
* @return string
*
*/
if (! function_exists('secret')) {
function secret($string, $action = 'e')
{
$secret_key = 'YourSecretKey';
$secret_iv = 'YourSecretIv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'e') { // default, encrypt
$output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
} else if ($action == 'd') { // decrypt
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment