How to verify password in the below code snippet - php

I have two questions here :
Is it fine using the openssl_random_pseudo_bytes() for generating random string or is it only better to take strings directly from /dev/random?
I've written the below code to generate a unique salt and a salted hash for each users password now how do i verify the password? I am confused on how to authorize because the hashes are random due to salts presence.

For 1: See here: https://security.stackexchange.com/a/101117
It answers perfectly what you're looking for.
For 2: For checking the password. First, you need the salt to check it, so you need to store the salt somewhere. Make 3 functions out of it:
function getSalt($length = 33) {
return openssl_digest(openssl_random_pseudo_bytes($length), 'sha512')
. openssl_digest('intercept9', 'sha512');
}
function encrypt($salt, $password) {
$password = md5($pass . $salt);
return $password;
}
function verify($salt, $password, $hash) {
return encrypt($salt, $password) == $hash;
}
$salt = getSalt();
$hash = encrypt($salt, 'root');
var_dump(verify($salt, 'root', $hash));
But try to rely on the password_* functions php already has implemented.

Related

using microtime() in password hash

i saw an example of password hashing using microtime() as this
public function create_hash($value)
{
return $hash = crypt($value, '$2a$12$'.substr(str_replace('+', '.', base64_encode(sha1(microtime(true), true))), 0, 22));
}
i want to know how could u can verify hash and make sure that the password entered by user is equal to the the password saved hashed in database while using microtime ?!
and that was the code for hash verify
private function verify_hash($password,$hash)
{
return $hash == crypt($password, $hash);
}
and how the last code works to verify hash ? ( the crypt method)
As of PHP 5.5, you can use password_hash() and password_verify() for hashing passwords much more conveniently than rolling with crypt().
To hash the password:
$hash = password_hash( $password, PASSWORD_DEFAULT );
Then to verify what the user has typed in against the hash:
if ( password_verify( $password, $hash )) {
// Password is good
}

PHP : Decrypt password from hash

So, I successfully encrypt a password to password hash using this following code :
class PassHash
{
// blowfish
private static $algo = '$2a';
// cost parameter
private static $cost = '$10';
// mainly for internal use
public static function unique_salt()
{
return substr(sha1(mt_rand()), 0, 22);
}
// this will be used to generate a hash
public static function hash($password)
{
return crypt($password, self::$algo .
self::$cost .
'$' . self::unique_salt());
}
// this will be used to compare a password against a hash
public static function check_password($hash, $password)
{
$full_salt = substr($hash, 0, 29);
$new_hash = crypt($password, $full_salt);
return ($hash == $new_hash);
}
}
and this is how I encrypting the password :
$password_hash = PassHash::hash($user->getPasswordHash());
But I have a little problem now when I try to display the password in normal mode.
What is the best way to decrypt the password from that hash ?
You can't decrypt a hash (well... technically you can, but you shouldn't) that's what hashes are for (not to be decrypted). You'll want to encrypt(hash) the password you received with the same hashing algorithm you used for the stored hash, and compare the hashes with eachother.
$password_hash = PassHash::hash($user->getPasswordHash());
if($stored_password === $password_hash){
//The passwords are the same
}
All in all you don't want to let anyone (not even yourself) know what the password of a user is (or the hash for that matter). The user will know, because he entered it and remembers it (hopefully anyway). No one else has got anything to do with seeing the user's password/hash. Letting anyone else but the user see/know the password/hash is a serious security issue.
On a different note: You should use the default implementations for hashing. Using your own hashing algorithm will always be worse than the true tried and tested methods. I'm not sure what PHP version you're using, but from PHP 5.5 onwards you can use password_hash(). For more information please view this question.

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.

Bcrypt class generating different hashes?

This is absolutely driving me crazy.
When registering an account I store the output of generateHash in the database.
I then generateHash again using the same $pattern when people try to log in.
However, the class generates a different hash. Even though I used the same pattern and password. This seems illogical.
class class_bcrypt
{
public function generateHash($pattern, $password)
{
//generate salt
$salt = '$2y$13$';
$salt = $salt . md5(strtolower($pattern));
//generate hash
$hash = crypt($password, $salt);
$hash = substr($hash, 29);
return $hash;
}
}

Crypt function generetes the same hash for the same password

I'm trying to create an hashing function that, given a random salt, generates a password hash from it.
The problem is, that, if I enter the same password for two different users, the hash generated is the same for both.
Waht might be the problem?
public function generateSalt()
{
return $salt = substr(sha1(uniqid(rand(), true)), 0, 32);
}
public function pwdEncrypt($password, $salt)
{
$hash = crypt($password, '$2a$' . $salt . '$');
return $hash;
}
public function registerUser($nome, $email, $password, $permitions, $active)
{
$this->nome = $nome;
$this->email = $email;
$salt = $this->generateSalt();
$this->password = $this->pwdEncrypt($password, $salt);
//INSERT METHODS BELOW
}
That's not how you use crypt with blowfish ($2a$)
You need to specify the strength, and the salt at the end.
Try this crypt($password, '$2a$08$'.$salt);
Obviously increase the strength to improve security, at the expense of processing time.
I should also add, if you are using a PHP version greater than 5.3.7, you should use $2y$ for your blowfish algorithm, as an attack for $2a$ was discovered in 2011.
crypt() will return a hashed string using the standard Unix DES-based algorithm.
Standard DES-based hash has a two character salt from the alphabet "./0-9A-Za-z".
Since in your case the first three characters of the salt are always the same, the salt used is always the same.
Use
return $salt = substr(sha1(uniqid(rand(), true)), 0, 2);
and
$hash = crypt($password, $salt);

Categories