This is not my first time using CodeIgniter or Bcrypt, but it is my first time using a specific library of Bcrypt with CodeIgniter. I am having issue integrating thee two together.
Lets get to the code :
public function create_user($value) {
$this -> CI = get_instance(); // Get the CI instance
$this -> CI -> load -> library('bcrypt'); // Use this to load the library from within the model
$hash = $this -> CI -> bcrypt -> password_hash($value[":password"], PASSWORD_BCRYPT, array("cost" => 17)); Here is where things get shaky.
$value[":password"] = $hash; // Here I take the :password placeholder and update the clear text password with the bcrypt pasword
var_dump($value[":password"]); // This gives me NULL, I assume because I am getting errors with $hash = .......
........................................
as per manual with Password_compat :
BCRYPT also allows for you to define a cost parameter in the options
array. This allows for you to change the CPU cost of the algorithm:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" =>
10));
On my front end these are the errors I keep getting :
Message: Use of undefined constant PASSWORD_BCRYPT - assumed
'PASSWORD_BCRYPT'
Message: password_hash() expects parameter 2 to be long, string given
I made this into a library itself so I put it into application/librarys folder
This is the file
any help would be great. Thank you.
Okay well looking at this file (which was my old Bcrypt.php file)
You notice I do not have these lines added :
if (!defined('PASSWORD_DEFAULT')) {
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
Well the reason I removed them was because I had put the above snippet of code under the Class Bcrpyt { ... line which would cause an error.
Now I put this snippet code :
if (!defined('PASSWORD_DEFAULT')) {
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
Class Bcrypt {
This is all I had to do for it to work. Silly me! Now it works :
string(60)
"$2y$17$9qgFDbN3361DAQFilGZySuJ4czachQThuskoSj4DihkxjwGFqTx2e"
Related
I've been spending a few days troubleshooting a failure of certain passwords to validate in Laravel 9. The password testperson resolves to the hash $2y$10$5xc/wAmNCKV.YhpWOfyNoetCj/r3Fs5TyAskgZuIF/LEItWfm7rPW. A direct query on the corresponding database table confirms that this is the correct hash. Yet Laravel's authentication infrastructure rejects this password and denies authentication.
This is not universal. I have multiple passwords that are resolving correctly. For example, the password eo resolves to $2y$10$uNWYvMVmagIwQ2eXnVKLCOAK1QFQdcRtxbvlghf.Xpg0U1w.N./N2, and Laravel authenticates that password. The same mechanism creates both of these user records, though they have different permissions (indicated by boolean values on the record).
I tracked down the bug to the function password_verify, which was identified as returning false negatives in this Stack Overflow question and this Treehouse thread.
Specifically, here is the stack in Laravel that gets down to this failure point:
The login route calls \Illuminate\Foundation\Auth\AuthenticatesUsers::login via the controller class.
The login method calls \Illuminate\Foundation\Auth\AuthenticatesUsers::attemptLogin.
The attemptLogin method calls the attempt method of the controller's guard object.
\Illuminate\Auth\SessionGuard::attempt calls \Illuminate\Auth\SessionGuard::hasValidCredentials.
\Illuminate\Auth\SessionGuard::hasValidCredentials calls the validateCredentials method on the guard's provider object.
Illuminate\Auth\EloquentUserProvider::validateCredentials calls the check method on its hasher object.
Illuminate\Hashing\HashManager::check calls the check method on its driver.
Illuminate\Hashing\BcryptHasher::check calls Illuminate\Hashing\AbstractHasher::check.
Illuminate\Hashing\AbstractHasher::check calls password_verify.
After unwinding this entire stack, I ran the following code in the login method of the login controller:
$provider = $this->guard()->getProvider();
$credentials = $this->credentials($request);
$user = $provider->retrieveByCredentials($credentials);
$password_unhashed = $request['password'];
$password_hashed = $user->getAuthPassword();
$password_verify = password_verify($password_unhashed, $password_hashed);
logger('attemping login', compact('password_verify','password_unhashed','password_hashed'));
That dumps this context:
{
"password_verify": false,
"password_unhashed": "testperson",
"password_hashed": "$2y$10$5xc/wAmNCKV.YhpWOfyNoetCj/r3Fs5TyAskgZuIF/LEItWfm7rPW"
}
And if I put that password into a SELECT users WHERE password= query, I get the user that I'm expecting.
What's going on here? And how do I get around this?
I think your assertion that the hash you provided is a hash of 'testperson' is in fact false. Since hashing is one-way, I can't tell you what the hash you showed is derived from. NOTE: This runs on PHP 7.4, but I don't think it will work on PHP 8 and beyond because of the deprecation of the salt option in password_hash().
<?php
//$testhash = '$2y$10$5xc/wAmNCKV.YhpWOfyNoetCj/r3Fs5TyAskgZuIF/LEItWfm7rPW';
$testhash = '$2y$10$uNWYvMVmagIwQ2eXnVKLCOAK1QFQdcRtxbvlghf.Xpg0U1w.N./N2';
//$password = "testperson";
$password = "eo";
$options = array("cost" => 10, "salt" => substr($testhash, 7, 22));
$pwhash = password_hash($password, PASSWORD_BCRYPT, $options);
echo $pwhash."\n";
$salt = substr($pwhash, 0, 29);
echo $salt."\n";
$cryptpw = crypt($password, $salt);
echo $cryptpw."\n";
if (password_verify($password, $cryptpw)) {
echo("Verified.\n");
} else {
echo("NOT Verified.\n");
}
if (password_needs_rehash($cryptpw, PASSWORD_BCRYPT, $options)) {
echo("Needs rehash.\n");
} else {
echo("Doesn't need rehash.\n");
}
/*
testperson results...
$2y$10$5xc/wAmNCKV.YhpWOfyNoeVNPMEcYrxepQeFAssFoAaIYs4WLmgZO
$2y$10$5xc/wAmNCKV.YhpWOfyNoe
$2y$10$5xc/wAmNCKV.YhpWOfyNoeVNPMEcYrxepQeFAssFoAaIYs4WLmgZO
Verified.
Doesn't need rehash.
eo results...
$2y$10$uNWYvMVmagIwQ2eXnVKLCOAK1QFQdcRtxbvlghf.Xpg0U1w.N./N2
$2y$10$uNWYvMVmagIwQ2eXnVKLCO
$2y$10$uNWYvMVmagIwQ2eXnVKLCOAK1QFQdcRtxbvlghf.Xpg0U1w.N./N2
Verified.
Doesn't need rehash.
*/
?>
I have a call to Hash::make in the observer for the user class. I discovered that it was running even though it wasn't supposed to, resulting in a duplicate hash.
I have set the encryption key in config.php file
$config['encryption_key'] = 'az2x#_.#!`~$aezxqy+=#%^&';
I want to use this key in password when registering users into the website, right now i am using this method
'password' => hash('sha256', $password . 'az2x#_.#!`~$aezxqy+=#%^&')
Is there any way i can set the above code like
'password' => hash('sha256', $password . $config['encryption_key']),
when i do it gives error of undefined $config variable.
I strongly suggest using the built-in php API for password salt/hash and not the method you are using, the encryption key is meant to be used for the encryption class...
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
You use this salted and hashed password stored in the database.
Then verify it when getting it from the DB using:
password_verify($password, $result->password)
This returns a BOOLEAN so you use it in an if statement:
if ( password_verify($password, $result->password) ) {
// do login stuff
} else {
// handle login failure
}
Else, you can use the encryption key by the following (strongly suggest against it):
$this->config->item('encryption_key');
If this doesn't work you are probably writing a helper or something, so you'll need to call the CI instance to get access to the config array.
I tried to reset password of wordpress admin panel.
I type some password and select function MD5.
It shows exact md5 conversion of the given string.
After log-in in admin panel of wordpress, if we browse the table it converts the password in some other string.
Can any one guide me about the password technique ?
Thanks
Quoting from the Wordpress docs
Creates a hash of a plain text password. Unless the global $wp_hasher is set, the default implementation uses PasswordHash, which adds salt to the password and hashes it with 8 passes of MD5. MD5 is used by default because it's supported on all platforms. You can configure PasswordHash to use Blowfish or extended DES (if available) instead of MD5 with the $portable_hashes constructor argument or property (see examples).
It uses the wp_hash_password function.
function wp_hash_password($password) {
global $wp_hasher;
if ( empty($wp_hasher) ) {
require_once( ABSPATH . WPINC . '/class-phpass.php');
// By default, use the portable hash from phpass
$wp_hasher = new PasswordHash(8, true);
}
return $wp_hasher->HashPassword( trim( $password ) );
}
The source coude of the "class-phpass.php" file can be found on the site: https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/class-phpass.php
I am trying to test the password_hash method for this purpose i have created the following function hashPassword:
function hashPassword($string) {
$settings = array('cost' => 10, 'encryption_key' => 'thisIsMyEncryptionKey1234');
return password_hash($string, PASSWORD_BCRYPT, $settings);
}
Now if i test this with a random string like "test"
The result would be:
$2y$10$thisIsMyEncryptionKeyu5n3NNnKh3DjgJqgb5pE8YOLBclKrVWC
Or if i test it with helloworld:
$2y$10$thisIsMyEncryptionKeyuVw8QRVNw8HbEWHX2oQlArVtne2TzOpS
Can anyone tell me why this is happening? Or is it suppose to be like this?
You should never provide the encryption key manually unless you have a very good reason to do so. I'd recommend reading the docs on password_hash some more.
Proper usage just lets the system figure it all out on its own:
function hashPassword($password)
{
return password_hash($password, PASSWORD_DEFAULT);
}
PHP will then internally choose the best available algorithm and most fitting number of iterations for current hardware, and generate a safe and unique salt.
To validate the password, then use password_verify, and check for required rehashes, for example in a User class:
class User
{
...
public function verifyPassword($password)
{
if(!password_verify($password, $this->hash))
return false;
if(password_needs_rehash($this->hash, PASSWORD_DEFAULT))
$this->setNewHashAndSaveToDB(password_hash($password, PASSWORD_DEFAULT));
return true;
}
}
By using this construct, you ensure hashed passwords are always kept up to date and secure as hardware capacities progress, automatically when a user logs in.
The policy on what algorithm PASSWORD_DEFAULT chooses, and with which config, is as follows:
Updates to supported algorithms by this function (or changes to the
default one) must follow the follwoing rules:
Any new algorithm must be in core for at least 1 full release of PHP prior to becoming default. So if, for example, a new algorithm
is added in 5.5.5, it would not be eligible for default until 5.7
(since
5.6 would be the first full release). But if a different algorithm was added in 5.6.0, it would also be eligible for default at 5.7.0.
The default should only change on a full release (5.6.0, 6.0.0, etc) and not on a revision release. The only exception to this is
in an emergency when a critical security flaw is found in the
current default.
About Encryption key:
Best Encrуption kеy is a binary blob that's gеnеrated from a rеliablе random numbеr gеnеrator. Thе following еxample would bе rеcommеndеd (>= 5.3):
$keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB);
$encryptionKey = openssl_random_pseudo_bytes($key_size, $strong); //$strong will be true if the key is crypto safe
But in your case you just set the string, use some random data for this.
I am using bcrypt to hash my passwords and it seems that symfony2 authentication system is not production the same hash as php's native crypt function. Bellow is the salt that I am generating for my user password:
$salt = '$2y$13$' . substr(md5(uniqid(rand(), true)),0,21) . '$';
$this->setPassword('test',$salt);
In my security.yml file I am simply doing:
encoders:
Blogger\BlogBundle\Entity\User:
algorithm: bcrypt
iterations: 13
Is there any reason why the two encoding methods would generate different hashes? The library I am using is ircmaxell/password-compat.
Best way to use this within Symfony2 is to use get the encoder.
use \Blogger\BlogBundle\Entity\User;
$user = new User();
$encoderFactory = $this->get('security.encoder_factory');
$encoder = $encoderFactory->getEncoder($user);
$salt = 'salt'; // this should be different for every user
$password = $encoder->encodePassword('password', $salt);
$user->setSalt($salt);
$user->setPassword($password);
If you are using FOSUserBundle, you should use:
use \Blogger\BlogBundle\Entity\User;
$userManager = $this->get('fos_user_manager');
$password = 'password';
$user = new User();
$user->setPlainPassword($password);
$userManager->updateUser($user, true); // second argument tells user manager to flush
After reviewing the source code for Symfony2.3 implementation of bcrypt, they use a function called hash_algorithm() and it seems to yield different results than crypt(). Both use $2y$ versions of bcrypt and I had set the cost for both algorithms to 13 ... however it is more consistent to do the following for setting passwords instead:
$user->setPassword(password_hash($user->getPassword(), PASSWORD_BCRYPT, array('cost' => 13)));
That line of code seemed to fix my problem. The best part is that I don't even have to generate my salt any more.