Your cart is currently empty!
How to Encrypt and decrypt a string in laravel
Hi guys,
In this tutorial, we’ll learn how to encrypt and decrypt a string in Laravel. AES-256 and AES-128 encryptions are provided by Laravel using the OpenSSL algorithm. To encrypt information, Laravel employs a message authentication code. After encrypted values not be modified.
Configuration:-
After running the command php artisan key:generate. It will generate secure random bytes to build your code. If this value is not set accurately, all values encrypted by laravel will be insecure.
Using The Encrypter:-
You are encrypting a value using an encrypting method of Crypt Facade. They encrypt all encrypted values with OpenSSL and AES-256-CBC cipher.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
class UserController extends Controller
{
/**
* Store secret message for the user.
*
* @param Request $request
* @param int $id
* @return Response
*/
public function storeSecret(Request $request, $id)
{
$user = User::findOrFail($id);
$user->fill([
'secret' => Crypt::encryptString($request->secret),
])->save();
}
}
DecryptString:
You can decrypt values using the decryptString method of Crypt Facade. If the value does not decrypt well, it will throw an exception of DecryptException.
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
try {
$decrypted = Crypt::decryptString($encryptedValue);
} catch (DecryptException $e) {
//
}
I hope that this post (How To Encrypt And Decrypt A String In Laravel) has helped you figure out how to set up the encryption key. It can also encrypt and decode strings. I used this site to write this post. Please leave a remark if you have any queries, and I will answer as quickly as possible.
Thank you for reading this article. Please share this article. That’s it for the day. Stay Connected!
Cheers,