password_verify for Phalcon Encryption Library - php

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)

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.

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.

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');

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.

Phalcon PHP Password Bcrypt

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.

Categories