Check Parse.com password manually - php

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

Related

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)

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.

Does this code use Bcrypt or just plain blowfish?

I'm learning php security online (using php 5.4) and came across the following code that I'd like to learn about/use. Does the following code use bcrypt and is it a good implementation of blowfish?
If problems exist, can you please suggest a fix or resource. Thanks.
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);
}
}
Here is the usage during user registration:
// include the class
require ("PassHash.php");
// ...
// read all form input from $_POST
// ...
// do your regular form validation stuff
// ...
// hash the password
$pass_hash = PassHash::hash($_POST['password']);
// store all user info in the DB, excluding $_POST['password']
// store $pass_hash instead
// ...
And here is the usage during a user login process:
// include the class
require ("PassHash.php");
// read all form input from $_POST
// ...
// fetch the user record based on $_POST['username'] or similar
// ...
// ...
// check the password the user tried to login with
if (PassHash::check_password($user['pass_hash'], $_POST['password']) {
// grant access
// ...
} else {
// deny access
// ...
}
Short answer :
Yes it does use bcrypt blowfish (in PHP blowfish is the current algorithm for bcrypt)
Correct answer :
Why not use a trusted PHP compatibility library like this one?
The benefits of using this over the one you posted? :
It is widely used by many people (must be trusted and well taken by the community)
Allow for forward compatibility with php 5.5 native bcrypt function (hence name for passwd_compat) more info here : Info Here!
Allows for a rehash which is genius (pretty much if you decide to crank up the cost of the algorithm you can easily do so and check if the cost matches the one in the library file if not then you can just update the password)
Bottom line : You can only go wrong with bcrypt if you don't know what your doing. One thing to remember is : do not reinvent the wheel if there are already wheels out there.
Hopefully this answer can help you out / expand your knowledge.

Categories