Phalcon PHP Password Bcrypt - php

So, I have setup in my di, the security component, as such...
--services.php--
$di->set('security', function(){
$security = new Phalcon\Security();
//Set the password hashing factor to 11 rounds
$security->setWorkFactor(11);
return $security;
}, true);
--Custom Auth Library (auth.php)--
$user = Users::findFirstByEmail($login);
if ($user) {
if ($this->security->checkHash($password, $user->password)) {
return true;
}
}
return false;
but, for some reason, this always returns false...so, to debug, I tried using PHP's password_verify function, the following code is in my view directly:
//Returns false
var_dump($this->security->checkHash('password', '$2a$12$aSa7zLEd24zjh2aoUasxd.hbxIm8IQ0/vMf/8p4LTYI3VtZMJ62Pe'));
//Returns True
var_dump(password_verify('password', '$2a$12$aSa7zLEd24zjh2aoUasxd.hbxIm8IQ0/vMf/8p4LTYI3VtZMJ62Pe'));
What am I missing???

Okay, so it seems that if I set both the hash, and the password to a variable, it parses both statements correctly.
I appreciate all of the help, but this was the final solution.
$password = $pass;
$hash = '$2a$12$lDL2eQ1GLJsJhKgPvU6agOnHpwNSBYPtWHF/O/aTvyISzI.ugjyLC';
var_dump($this->security->checkHash($password, $hash));
var_dump(password_verify($password, $hash));

This might be related to Security::checkHash returns true when using with a non-bcrypt hash, which has been fixed a few days ago.
Looking at the code, the problem might be within this block, can you verify that the user model gets loaded, so does his hashed password?
$user = Users::findFirstByEmail($login);
if ($user) {
if ($this->security->checkHash($password, $user->password)) {
return true;
}
}
return false;

In case someone gets here and none of the answers above seem to help, and you keep feeling more and more dumb, check the password column length in your users table!!. In my case it was a varchar(50) and the hash gives you 60 chars.
Doing this (pointed above) http://pastebin.com/6tNRgyXg, helped me realise that something other than the code was wrong.

Related

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)

How to create a laravel hashed password

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.

Identical Phpass code returning different results with CheckPassword

I am using Phpass to hash the passwords of my users. The creation and hashing of the password - fine. The checking of the password when logging in - fine.
The checking of the old password when changing it to a new one though - always returns false!
It is basically the same code but it never returns true, even when the password is correct. I have tried just checking the password outright by typing a password and pasting its hash into the function instead of calling it from the database and the input form but that still returns false.
Here is the login code which works:
$user = $query->fetch(PDO::FETCH_ASSOC);
$t_hasher = new PasswordHash(8, FALSE);
$check = $t_hasher->CheckPassword($password, $user['password']);
if (!$check) { die("failed"); }
else { ... log them in etc.
And here is the change password check, which doesn't work:
$user = $query->fetch(PDO::FETCH_ASSOC);
$t_hasher = new PasswordHash(8, FALSE);
$check = $t_hasher->CheckPassword($oldpass, $user['password']);
if (!$check) { showMessage("Incorrect Password","Your password was not changed.","icon-lock", "warning"); }
else { ... change the password etc.
I am at a loss, as far as I can see there is no conceivable reason why this isn't working.
It turns out I am a massive idiot and forgot to execute the database query for the change password.

Categories