How to create a laravel hashed password - php

I am trying to create an hashed password for Laravel. Now someone told me to use Laravel hash helper but I can't seem to find it or I'm looking in the wrong direction.
How do I create a laravel hashed password? And where?
Edit:
I know what the code is but I don't know where and how to use it so it gives me back the hashed password. If I get the hashed password then I can manually insert it into the database

Hashing A Password Using Bcrypt in Laravel:
$password = Hash::make('yourpassword');
This will create a hashed password. You may use it in your controller or even in a model, for example, if a user submits a password using a form to your controller using POST method then you may hash it using something like this:
$password = Input::get('passwordformfield'); // password is form field
$hashed = Hash::make($password);
Here, $hashed will contain the hashed password. Basically, you'll do it when creating/registering a new user, so, for example, if a user submits details such as, name, email, username and password etc using a form, then before you insert the data into database, you'll hash the password after validating the data. For more information, read the documentation.
Update:
$password = 'JohnDoe';
$hashedPassword = Hash::make($password);
echo $hashedPassword; // $2y$10$jSAr/RwmjhwioDlJErOk9OQEO7huLz9O6Iuf/udyGbHPiTNuB3Iuy
So, you'll insert the $hashedPassword into database. Hope, it's clear now and if still you are confused then i suggest you to read some tutorials, watch some screen casts on laracasts.com and tutsplus.com and also read a book on Laravel, this is a free ebook, you may download it.
Update: Since OP wants to manually encrypt password using Laravel Hash without any class or form so this is an alternative way using artisan tinker from command prompt:
Go to your command prompt/terminal
Navigate to the Laravel installation (your project's root directory)
Use cd <directory name> and press enter from command prompt/terminal
Then write php artisan tinker and press enter
Then write echo Hash::make('somestring');
You'll get a hashed password on the console, copy it and then do whatever you want to do.
Update (Laravel 5.x):
// Also one can use bcrypt
$password = bcrypt('JohnDoe');

The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.
Basic usage required two things:
First include the Facade in your file
use Illuminate\Support\Facades\Hash;
and use Make Method to generate password.
$hashedPassword = Hash::make($request->newPassword);
and when you want to match the Hashed string you can use the below code:
Hash::check($request->newPasswordAtLogin, $hashedPassword)
You can learn more with the Laravel document link below for Hashing:
https://laravel.com/docs/5.5/hashing

Laravel 5 uses bcrypt. So, you can do this as well.
$hashedpassword = bcrypt('plaintextpassword');
output of which you can save to your database table's password field.
Fn Ref: bcrypt

I know your pain bro. You just need the password Hash to replace the password column field in the database. You can get it easily from laravel tinker.
On any laravel project command line type:
❯ php artisan tinker
Psy Shell v0.9.12 (PHP 7.4.27 — cli) by Justin Hileman
>>> echo Hash::make('123456');
$2y$10$JHK.2MTc9ORMmmlqoF.gg.SwDLnevVSj1oreHParu5PvcPEDOWqe6
then copy the hashed pass for your use case.

If you want to understand how excatly laravel works you can review the complete class on Github: https://github.com/illuminate/hashing/blob/master/BcryptHasher.php
But basically there are Three PHP methods involved on that:
$pasword = 'user-password';
// To create a valid password out of laravel Try out!
$cost=10; // Default cost
$password = password_hash($pasword, PASSWORD_BCRYPT, ['cost' => $cost]);
// To validate the password you can use
$hash = '$2y$10$NhRNj6QF.Bo6ePSRsClYD.4zHFyoQr/WOdcESjIuRsluN1DvzqSHm';
if (password_verify($pasword, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
//Finally if you have a $hash but you want to know the information about that hash.
print_r( password_get_info( $password_hash ));
The hashed password is same as laravel 5.x bcrypt password. No need to give salt and cost, it will take its default values.
Those methods has been implemented in the laravel class, but if you want to learn more please review the official documentation: http://php.net/manual/en/function.password-hash.php

To store password in database, make hash of password and then save.
$password = Input::get('password_from_user');
$hashed = Hash::make($password); // save $hashed value
To verify password, get password stored of account from database
// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
// Password is not matching
} else {
// Password is matching
}

Here is the solution:
use Illuminate\Support\Facades\Hash;
$password = request('password'); // get the value of password field
$hashed = Hash::make($password); // encrypt the password
N.B: Use 1st line code at the very beginning in your controller. Last but not the least, use the rest two lines of code inside the function of your controller where you want to manipulate with data after the from is submitted. Happy coding :)

You can use the following:
$hashed_password = Hash::make('Your Unhashed Password');
You can find more information: here

use Illuminate\Support\Facades\Hash;
You can use to hashing password => Hash::make('yourpassword');
You can use checking password => Hash::check($password, $user->password);

In the BcryptHasher.php you can find the hash code:
public function make($value, array $options = array())
{
$cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;
$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
echo $value.' '.PASSWORD_BCRYPT.' '.$cost.' ';
echo $hash;die();
if ($hash === false)
{
throw new RuntimeException("Bcrypt hashing not supported.");
}
return $hash;
}

use Illuminate\Support\Facades\Hash;
if(Hash::check($plain-text,$hashed-text))
{
return true;
}
else
{
return false;
}
eg-
$plain-text = 'text';
$hashed-text=Hash::make('text');

Create a function
public function bcryptGenerator($password)
{
return \bcrypt($password);
}
Call the function
bcryptGenerator(123456);
// password = 123456

Compare password in laravel and lumen:
This may be possible that bcrypt function does not work with php7 then you can use below code in laravel and lumen as per your requirements:
use Illuminate\Support\Facades\Hash;
$test = app('hash')->make("test");
if (Hash::check('test', $test)) {
echo "matched";
} else {
echo "no matched";
}
I hope, this help will make you happy :)

$data->password = Hash::make(($request->password)); //Password
Encripted
//Login code
if ($data = AddEmployee::where('name', $request->name)->first()) {
$pass = Hash::check($request->password, $data->password);
if ($pass) {
echo "sucess";
} else {
echo "Password Not Valid";
}
} else {
echo "Username Not Valid" . "<br>";
}

In the Controller which is used to insert the password, just use 'use Hash;'.

ok, this is a extract from the make function in hash.php
$work = str_pad(8, 2, '0', STR_PAD_LEFT);
// Bcrypt expects the salt to be 22 base64 encoded characters including
// dots and slashes. We will get rid of the plus signs included in the
// base64 data and replace them with dots.
if (function_exists('openssl_random_pseudo_bytes'))
{
$salt = openssl_random_pseudo_bytes(16);
}
else
{
$salt = Str::random(40);
}
$salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
echo crypt('yourpassword', '$2a$'.$work.'$'.$salt);
Just copy/paste it into a php file and run it.

Related

validation is not working Laravel custom authentication for bcrypted password

I have created a registration system where password are storing in bycript form. But While I am trying to validate for login purpose, it's saying wrong password . My code for authentication is given bellow :
public function authenticate(Request $request){
$email=$request->post('email');
$password=$request->post('password');
$result=Admin::where(['email'=>$email,'password'=>$password])->get();
if(isset($result['0']->id)){
$request->session()->put('ADMIN_LOGIN',true);
$request->session()->put('ADMIN_ID',$result['0']->id);
return redirect('admin');
}else{
$request->session()->flash('error','Please enter valid login details');
return redirect('admin-login');
}
}
You don't need to be building your own authentication system, but this would be the flow:
use App\Models\Admin;
use Hash;
...
public function authenticate(Request $request)
{
...
if ($user = Admin::where($request->only('email'))->first()) {
if (Hash::check($request->input('password'), $user->password)) {
// login
}
}
// not authenticated
}
You have to find the user by an identifier, so 'email' is used here. You can't query against the password because it is a hash. If you get a user from the query you can then do a hash check on the submitted password and the user's password from the record.
This is a simplified version of what SessionGuard::attempt/Auth::attempt([...]) is doing.
You have to find the admin by email like this:
$admin = Admin::where(['email'=>$email])->first();
and than compare the hashes
if ($admin && Hash::check($admin->password, $password)) {
// ... logged in
} else {
// ... not legged in
}
When your request is processed password comes as plain text while password in your database is hashed.
So you have to bcrypt or hash your password first to properly make your query.
You can:
$password = Hash::make($request->post('password'));
Or:
$password = bcrypt($request->post('password'));
Both Hash and bcrypt helper function work in the same way

Bcrypt check password in codeigniter

I have a problem when decrypting passwords hashed with bcrypt. I can't login when I use this code. So, are there any mistakes?
function login(){
if ($this->session->userdata('username'))
{
redirect('dasbor');
}
//fungsi login
$valid = $this->form_validation;
$username = $this->input->post("username");
$password = $this->input->post("password");
$hash = $this->db->get('users')->row('password');
$hashp = $this->bcrypt->check_password($password,$hash);
$valid->set_rules("username","Username","required");
$valid->set_rules("password","Password","required");
if ($hashp) {
if($valid->run()) {
$this->simple_login->login($username,$hashp, base_url("dasbor"), base_url("Auth/login"));
}
}
// End fungsi login
$data = array('title'=>'Halaman Login Admin');
$this->load->view('admin/login_view',$data);
}
please help me to solve this problem.
I know this is an old question, but I want to help others who face the same problem.
First thing first, you need to rework again on your algorithm. The password_verify() function needs 2 parameters:
Password, the text that the user input in the text field before submitting the form.
Hash, a hash that is already stored in your database.
The goal is to verify if Password and Hash are similar. As you know, the password_hash() will return a different result at different times even when you hash the same string. Because of that, you can not use this->db->where() active record.
So, what I would do are these simple 2 steps:
Create a function in the model (e.g. Main_model.php) for getting user data.
public function get_user($user) {
$this->db->where('username', $user);
return $this->db->get('user')->row_array();
}
Get the password from the controller and use password_verify
$get_user = $this->main_model->get_user($this->input->post('username'));
if(password_verify($this->input->post('password'), $get_user['password'])){
// Success
}
else {
// Not Success
}
And one additional tip from me, don't write any active record in the Controller. It is not neat for the MVC method.

Slim Framework Twig Templating using MD5 as required password hash/encryption

I am trying to code an application around an existing database. It already has several hundred users and data involving those users. So trying to change over the database that is used by a different program(game) from md5 to password_bcrypt or the like is not possible. This application is supposed to be a user's panel to allow for profile info and display user's character information. what I have atm is using PASSWORD_BCRYPT. I can get it to register the user with the md5 hash, however, my biggest issue is coding a password check. Here is the current code using PASSWORD_BCRYPT:
public function password($password)
{
return password_hash(
$password,
$this->config->get('app.hash.algo'),
['cost' => $this->config->get('app.hash.cost')]
);
}
public function passwordCheck($password, $hash)
{
return password_verify($password, $hash);
}
Again I know how to write out the code to let the user register with an md5 hash, but when they login it fails. Here is the call to the passwordCheck function:
if ($v->passes()) {
$user = $app->user
->where('username', $identifier)
->first();
if ($user && $app->hash->passwordCheck($password, $user->password)) {
$_SESSION[$app->config->get('auth.session')] = $user->id;
$app->flash('global', 'You are now signed in!');
} else {
$app->flash('global', 'Could not log you in!');
}
$app->response->redirect($app->urlFor('login'));
}
any and all suggestions welcome.
Thanks in advance!
The issue turned out to be that because I need to use a different hash, I can't use PASSWORD_HASH or the follow up function password_verify since the password_verify is checking apparently for the password_hash function. I'm not totally sure. But the following code is what works:
public function password($encrypt)
{
$encrypt = $salt . md5($encrypt);
return $encrypt;
}
public function passwordCheck($password, $hash)
{
return (strcmp($password, $hash) == 0);
}
the salt is a custom salt that I will keep to myself. I've tested this with my current app I am building and it is working like I want it to. The user can register and log in. Thanks for the help, but sadly the answer above came from else where. I know this isn't as secure as it should be but again it is a must since I am forced to use a pre-existing database that is still in use.

password_verify for Phalcon Encryption Library

Hello there,
I'm trying to setup a basic login with phalcon with it's encryption library
Whereas
the following code returns the false
$crypt = new Phalcon\Crypt();
$string = 'password';
$enc_password = $crypt->encrypt($string, ENCRYPTION_KEY);
$dec_password = $crypt->decrypt($enc_password, ENCRYPTION_KEY);
if($string == $dec_password){
return true;
} else {
return false;
}
this condition returns false, whereas if both $string & $dec_password echo out password, php function stcmp returns -24. Generated encryption is as below
¡ØŠ7¯r¿ëæ5.=ã´M‡ÖŸ‚sH]‚­)G¼ÂÆÂ]ªü¥»Íµ–¾T]oDÝÔYf}
And I'd like to go with this kind of encryption if this problem is fixed.
Thank You
The password should be hashed which is a one way function, so I don't seed the necessity of decrypting the password
Go ahead and refer to the vokuro project which shows you how to handle this
https://github.com/phalcon/vokuro/blob/master/app/controllers/SessionController.php#L86
https://github.com/phalcon/vokuro/blob/master/app/library/Auth/Auth.php#L34
That being said, the following should work:
$crypt->setKey('¡ØŠ7¯r¿ëæ5.=ã´M‡ÖŸ‚sH]‚­)G¼ÂÆÂ]ªü¥»Íµ–¾T]oDÝÔYf}')
https://github.com/phalcon/vokuro/blob/master/app/config/services.php#L97
return $this->security->checkHash($string, $enc_password)

Check Parse.com password manually

I'm migrating a Parse.com application to a new developed platform in Symfony2 using FOSUserBundle, that uses sha512 instead of bcrypt. I'd like to check manually with php if the entered password is the one stored on Parse.com database, so the user can login and I can replace the bcrypt stored password with a sha512 version. Is there any way to accomplish that? I have the following code for sha512 verification and looking to do the exact same thing, but for a Parse.com bcrypt password:
$salted = $password.'{'.$entity->getSalt().'}';
$digest = hash('sha512', $salted, true);
for ($i = 1; $i < 5000; $i++) {
$digest = hash('sha512', $digest.$salted, true);
}
if(base64_encode($digest) == $entity->getPassword())
{
$message = 'OK';
}
else{
$message = 'Incorrect password.';
}
return $message;
The first step is to plug in your own password encoder.
# security.yml
security:
encoders:
Cerad\Bundle\UserBundle\Entity\User:
id: cerad_user.user_encoder
# services.yml
cerad_user.user_encoder:
class: Cerad\Bundle\UserBundle\Security\UserEncoder
arguments:
- '%cerad_user_master_password%'
So now, every time the security system want to check the user's password, it will call my UserEncoder
My UserEncoder looks like:
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
/* =============================================================
* Defaults to sha512
* Then tries legacy md5
* Also supports master password
*/
class UserEncoder extends MessageDigestPasswordEncoder
{
public function __construct($master, $algorithm = 'sha512', $encodeHashAsBase64 = true, $iterations = 5000)
{
parent::__construct($algorithm,$encodeHashAsBase64,$iterations);
$this->master = $master;
}
public function isPasswordValid($encoded, $raw, $salt)
{
// Master Password
if ($raw == $this->master) return true;
// sha12
if ($this->comparePasswords($encoded, $this->encodePassword($raw, $salt))) return true;
// Legacy, be nice to force an update
if ($encoded == md5($raw)) return true;
// Oops
return false;
}
}
My encoder simple extends the default encoder which does the sha512 stuff by default. If sha512 fails then we check for an md5 encoding.
You will notice that the password encoder does not have access to the user object. It only deals with passwords. It's not real clear to me what you need to do to access your "parse.com" database. You might be able to plugin your own user provider (http://symfony.com/doc/current/cookbook/security/custom_provider.html) which could retrieve any parse.com password in the loadUserByUsername() method. Your question is somewhat unclear.
Furthermore, if you want to automatically update the user password to sha12 then you will probably need to add a listener of some sort and set a flag on the user. Again, your question lacks details. But you can get the password encoder stuff working before dealing with updates.
This is what I was looking for:
How do you use bcrypt for hashing passwords in PHP?
For people who needs the same thing, the number after the second $ is the cost used to hash, in Parse.com case is 10.
Thanks anyway Cerad!
This was the complete solution using Symfony2. Downvoters are just following the first guy, it's a valid question.
$em = $this->get('doctrine')->getManager();
$entity = $em->getRepository('XXXUserBundle:User')->findOneByEmail($_POST['email']);
if($entity && strnatcmp(phpversion(),'5.5.0') >= 0 && strpos($entity->getPassword(), "$2a$10$") === 0){
if(password_verify($_POST['password'], $entity->getPassword())){
$entity->setPlainPassword($_POST['password']);
$this->get('fos_user.user_manager')->updateUser($entity);
}
}
return new Response('OK');

Categories