Laravel's application key - what it is and how does it work?
APP_KEY is used for encryption and not hashing. Every Data you encrypt in your application is using APP_KEY behind the scene. Do remember that encrypted data can be decrypted but hashed data cannot be decrypted.
A common misconception of APP_KEY is that it is related to Password hashing, the truth is it's not. and here is the proof.
taylor's tweet
You can see in the above tweet that APP_KEY has nothing to do with HASHED data
What is the significance of Application key in a Laravel Application?
As we can see its used in EncryptionServiceProvider
:
public function register()
{
$this->app->singleton('encrypter', function ($app) {
$config = $app->make('config')->get('app');
// If the key starts with "base64:", we will need to decode the key before handing
// it off to the encrypter. Keys may be base-64 encoded for presentation and we
// want to make sure to convert them back to the raw bytes before encrypting.
if (Str::startsWith($key = $this->key($config), 'base64:')) {
$key = base64_decode(substr($key, 7));
}
return new Encrypter($key, $config['cipher']);
});
}
So every component that uses encryption: session, encryption (user scope), csrf token benefit from the app_key
.
Rest of the questions can be answered by "how encryption" (AES) works, just open up Encrypter.php
, and confirm that Laravel uses AES under the hood and encodes the result to base64.
Further more we can see how its all done by using tinker:
➜ laravel git:(staging) ✗ art tinker
Psy Shell v0.8.17 (PHP 7.1.14 — cli) by Justin Hileman
>>> encrypt('Hello World!')
=> "eyJpdiI6ImgzK08zSDQyMUE1T1NMVThERjQzdEE9PSIsInZhbHVlIjoiYzlZTk1td0JJZGtrS2luMlo0QzdGcVpKdTEzTWsxeFB6ME5pT1NmaGlQaz0iLCJtYWMiOiI3YTAzY2IxZjBiM2IyNDZiYzljZGJjNTczYzA3MGRjN2U3ZmFkMTVmMWRhMjcwMTRlODk5YTg5ZmM2YjBjMGNlIn0="
Note: I used this key:
base64:Qc25VgXJ8CEkp790nqF+eEocRk1o7Yp0lM1jWPUuocQ=
to encryptHello World!
After decoding the result we get (you can try decode your own cookie with session):
{"iv":"h3+O3H421A5OSLU8DF43tA==","value":"c9YNMmwBIdkkKin2Z4C7FqZJu13Mk1xPz0NiOSfhiPk=","mac":"7a03cb1f0b3b246bc9cdbc573c070dc7e7fad15f1da27014e899a89fc6b0c0ce"}
to understand above json (iv
, value
, mac
) you need to understand AES:
- https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
Best practices for application key
- do store it in
.env
file only - do not store it in
app.php
, in fact in any git tracked file - do not change it unless you really want to
- invalidate sessions/cookies (user logout)
- invalidate password reset tokens
- invalidate signed urls
Obvious Note: Changing application key has no effect on hashed passwords since hashing algorithms do not require encryption keys.
What is the difference between application key and passport key in Laravel. What is the usage of both keys
First of all, they are not related. APP_KEY is used for everything that needs encryption and should be secret(sessions etc.). Passport keys are for API Authentication. For example: Twitter API needs 4 tokens in order for you to access data.
Is it ok if more than one developer use the same APP_KEY in Laravel for local development?
It is OK.
Since Laravel uses APP_KEY for encrypting cookies (I've just learnt that) including session cookie, it doesn't matter if the developers are using the same APP_KEY in their local environment.
On the other hand, it is important to produce new APP_KEY for the production environment and even change it regularly.
My resource: https://tighten.co/blog/app-key-and-you/
When to generate a new Application Key in Laravel?
php artisan key:generate
is a command that sets the APP_KEY
value in your .env
file. By default, this command is run following a composer create-project laravel/laravel
command. If you use a version control system like git
to manage your project for development, calling git push ...
will push a copy of your Laravel project to wherever it is going, but will not include your .env
file. Therefore, if someone clones your project using git clone ...
they will have to manually enter php artisan key:generate
for their app to function correctly.
So, TL:DR the only time you need to call php artisan key:generate
is following a clone
of a pre-created Laravel project.
Side note: If you try to run a Laravel project with your APP_KEY
set to SomeRandomString
(which is the default in your .env.example
file, you will actually get an error:
No supported encrypter found. The cipher and / or key length are invalid.
Laravel 5 Application Key
This line in your app.php
, 'key' => env('APP_KEY', 'SomeRandomString'),
, is saying that the key for your application can be found in your .env
file on the line APP_KEY
.
Basically it tells Laravel to look for the key in the .env
file first and if there isn't one there then to use 'SomeRandomString'
.
When you use the php artisan key:generate
it will generate the new key to your .env
file and not the app.php
file.
As kotapeter said, your .env
will be inside your root Laravel directory and may be hidden; xampp/htdocs/laravel/blog
Why is there 2 APP Key in Laravel? .env and config/app.php
The value set in config/app.php
is used if there is no value in the .env
file. If you have set the app key in the .env
file, the second argument in app.php
is ignored.
Is it necessary to execute php artisan key:generate command after installation of laravel 5.7
php artisan key:generate
This command sets the APP_KEY
value in your .env
file.
If you create a project with composer it'll generated default with project.
composer create-project laravel/laravel
If you clone project using git clone
some folder is ignored by git so you might not get env file as well as vendor folder. Therefore, they will have to manually enter php artisan key:generate
for their app to function correctly.
So, TL:DR the only time you need to call php artisan key:generate
is following a clone
of a pre-created Laravel project.
Note: If you try to run a Laravel project with your APP_KEY
set to SomeRandomString
(which is the default in your .env.example
file, you will actually get an error:
No supported encrypter found. The cipher and / or key length are invalid.
Related Topics
Access MySQL Field's Comments with PHP
Http Header for Downloading Microsoft Word and Excel Files
Xpath in Simplexml for Default Namespaces Without Needing Prefixes
Symfony & Guard: "The Security Token Was Removed Due to an Accountstatusexception"
How to JSON_Encode PHP Array But the Keys Without Quotes
Does PHP Feature Short Hand Syntax for Objects
Pdo Mssql Server - Driver Not Found
What Is the Rfc Compliant and Working Regular Expression to Check If a String Is a Valid Url
Why Don't PHP and JavaScript's Timestamps Match
PHP Post Limited to 1000 Variables
Php/Apache: PHP Fatal Error: Call to Undefined Function MySQL_Connect()
Why Do I Receive "This Value Should Be of Type String" When Using a Datetime Constraint on Symfony 5
Php: Re Order Associative Array
Setting $_Session Doesn't Work on Localhost Using Xampp
Extracting Matches from PHP Regex
How to Destroy Session with Browser Closing in Codeigniter