PHP md5 and sha1 confusion - Why am I getting different encryption results? - php

I have a php function in a php page called encrypt_password that I use when processing a registration form:
function encrypt_password($password){
$salt = sha1(md5($password));
$password = md5($password.$salt);
return $password;
}
I try to use it again for when I process the login form but I get a different result.
I get the correct result just by not calling this function and instead just calling:
$salt = sha1(md5($password));
$password = md5($password.$salt);
directly on my process_login page. Why would I get a different result by calling encrypt_password?
I hope I have explained this clearly enough!
Thanks!

I simply cannot believe this to be true. You say you have two pages, one with a registration form and one with a login form.
They both have to encrypt the password the user has posted.
There can be a number of things wrong here, depending on how you find they don't match. Do you just try to login and see an error that your password is wrong? Or did you echo the password hash after a call to encrypt_password? It would be nice to have done that to shown us a hash of the password 'test', from both the registration page and the login page. Perhaps someone could've seen a pattern.
Anyway, let me guess:
You enter the password incorrectly.
You have created this user you're testing it with, with an older version of your encryption function. Perhaps you only used md5(password) to register, then you read somewhere that was unsafe and added a salt. Now you're comparing two different hashes for the same password, since the password is stored in the database using the old hashing function.
You set $password with $password = $_POST['password']; I guess. On both pages, I guess too. Are those statements on both pages typo-free? No $password = $_POST['pasword']; there? And are both <input> elements named "password"?
Typos also go for the $encrypt_password function. Do you define it on both pages, or do you include it from another file? (You should!) If they exist in both files, do they match letter by letter? Copypaste it to test this, and if it works, thank me and put it in an include afterwards, and let it be a lesson.

i faced the same problem .
check the length of password field in db the value after hashed is increased the limit you specified in the db

Yep, I checked the code and theres is no error. This is my code without any flaws:
function encrypt_password($password){
$salt = sha1(md5($password));
$password = md5($password.$salt);
return $password;
}
$myPassword = "test";
echo encrypt_password($myPassword );
// this gives me 34364c859afb02e70306c905374ac2d5
$salt = sha1(md5($myPassword));
$password = md5($myPassword.$salt);
echo "<br />";
echo $password;
//this gives me 34364c859afb02e70306c905374ac2d5
So, they are the same. Like Dimme, I thought the same about variable names. But I could not replicate this. Sorry...

Related

Can a default user's password be set in SQL using PHP's password_hash?

My old PHP app has a default admin user and md5 encrypted password created by the SQL that creates the database: insert into users values ( 1, 'admin', MD5('changeMe'), 2 );
Is there a simple way to include a default user and encrypted password using PHP's passowrd_hash function on creating the tables? I ask because I understand that password_hash is a native PHP function and I assume it won't be understood in SQL.
The solution to my problem came in three parts. My OP sought a simple way to create a hashed password for the admin user for insertion in the MySQL database on the installation of the application, using the native PHP password_hash() function.
(1) Based on a suggestion by #Nick and #Tadman, I decided to incorporate setting the hash in an installer script that would set not only the hash but other defined site/application variables.
Rather than inserting user values when the database table is created, it was deferred until immediately after, with the admin user entering their credentials in the form that inserts the hash and writes other definitions to a file:
$userpass = $_POST['userpass'];
echo password_hash($userpass, PASSWORD_BCRYPT);
(2) The second part of my problem was replacing all instances of md5()`` withpassword_hash()` and I achieved that by using a neat PHP script I found online to recursively search and replace the occurrences on the server.
Having replaced the md5() occurrences, I needed to change the hash comparison method and again by searching the relevant files I was able to replace instances of:
if ($p != $theUser->pwd ) {
return( false ); }
with:
if(password_verify($p, $theUser->pwd)) {
// Success!
}
else {
// Invalid credentials
echo "Uh oh!";
}
(3) The third step in resolving the problem was discovering that adding $1$ to the opening of the md5 hash could make it readable by password_hash(); so I just needed to make a couple of adjustments in the installed database to the admin user's old password.
Thanks to those who helped shine the light so I could find my way. I'm off now to invent the wheel and sliced bread.
you can do something like this in php:
$hash = password_hash('changeMe');
//echo $hash;
then use this hash in the Database.

Password works even with extra characters

I have two methods that I am using. When a user creates an account I call this method to make a secure password hash for them to save into the database:
public function createPassword($password){
$salt = hash("sha256", time() . uniqid() . rand(1, 1000));
return crypt($password, $salt);
}
It returns a salt which I then save into the database in the password column.
Next when a user logs into his/her account I select their info from the database and pass it to this function which then is supposed to verify their password.
public function verifyPassword($password, $salt){
if(crypt($password, $salt) == $salt){
return true;
}
return false;
}
The issue is that I have found a password that if I put the correct password in it works, but if I add extra characters to the end of the password it still works. This shouldn't happen. am I doing something wrong or is this a bug in php?
For security I am not using the real password below
// Create during registration
$salt = $obj->createPassword('abc123');
// Save to database here
then:
// Get row from database save array $row
if($obj->verifyPassword($_POST["passwd"], $row["password"])){
// Log user in
}
Here are my tests:
abc123 // Works
abc12 // doesn't work
abc12jfjf // doesn't work
abc123123 // Works
abc123asdfadffa // Works
So, it looks as if as long as the string starts with the real password anything after is fine...
This may depend on the encryption method you are using. In your example, is the actually password you are using 8 characters?
If so, then any characters past the 8th are truncated.
https://bugs.php.net/bug.php?id=11240
To avoid this behavior, use MD5 encryption.

Using crypt () blowfish hash during login [duplicate]

This question already has an answer here:
bcrypt and randomly generated salts
(1 answer)
Closed 8 years ago.
* A REAL WORKING ANSWER is at the bottom of this page! *
This is a question about using crypt () blowfish hash during login for customer verification. I am restricted to PHP 5.3 by my web host and I know it would be better to use PHP 5.5 with password hash () and password verify() but PHP 5.3 doesn’t seem to recognize them. The problem is not hashing the password and putting it in the database the available codes on line work for that. The problem is all the codes I found (about ten so far) don’t take into consideration that the randomized salt that is highly recommended for the registration page can’t be used on login passwords because it will be different every time with no match. Is what I am trying to do not possible on PHP 5.3 or is there a way to re-hash the users password using the salt it was randomized with so it can be checked against the one stored in the database?
Codes like this work well for randomizing the salt and hashing the password for the database entry.
function better_crypt($input, $rounds = 9)
{
$salt = "";
$salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0; $i < 22; $i++) {
$salt .= $salt_chars[array_rand($salt_chars)];
}
return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt);
}
$password_hash = better_crypt($input);
But login codes like this don’t work and the functions from the registration page must be redefined on the login page some how. They don’t carry over like session variables. I know I must be missing something… Does anyone have a code that will work for this funtion?
$password_hash = better_crypt($db_password_hash);
if (crypt($user_password, $password_hash) == $password_hash) {
echo '<br>';
echo 'true';
}else{
echo '<br>';
echo 'false';
}
Can’t add comment at bottom of page… I don’t have permission?
The “better crypt” function is for the registration page, it could be called something else. I don’t think it is used for the login page or the PHP include page, but this is what I am asking. Is there a login function or code that can use the original salt and how do I get it out of the hashed password in the database to check it and verify the user?
About the answer (bcrypt and randomly generated salts)
How do I extract the original randomized salt from the hashed password stored in the database or do I try to separate it first during registration and save it separately to use during login? I read this not the way it is suppose to work.
Hi martinstoeckli … The link to “compatibility pack “ goes to the PHP manual on “password_hash”, I don’t see any compatibility pack. The algorithm is set by blowfish and it stays the same for every hashed password. Using crypt by itself is weaker then blowfish, but even that dose not solve the login problem I am asking about. I tried that frist.
If anyone has a working login code to use with blowfish ($2a$) algorithm and using any cost value, please post it. It needs to extract the salt from the saved hashed database password to hash the user enter password during login for comparison. Somehow... Using a fixed salt is not recommended so the randomized salt during registration must be extracted somehow from the saved hash password.
Hi deceze,
I did check the duplicate but it had no login code to try. I will try to make a new code to test using this one line below… where $passwordToCheck is the login password and $2y$10$abcdefg... is the stored hashed password in the database. I will put it in an “if statement and echo if it is true or else false”. Get back to you with the results…Thanks
crypt($passwordToCheck, '$2y$10$abcdefg...')
deceze,
I tried this code below with the “,” and “==” both return true or “worked!” with any password input into the login. Please post the code you use for your login page so I can test or modify it to use on mine .
if
(crypt($user_password == $db_password_hash)){
echo '<br>';
echo ' Worked! ';
echo '<br>';
}
else
{
echo '<br>';
echo ' Did not work ): ';
echo '<br>';
}
Also I am using “$2y$11$” now for the algorithm and cost parameter on my registration page with database input like this “$2y$11$9MUd40QqfmmtPaes91OttOlvAhkAtMvS4.mtg9LT.tazythwhRMwu”
Would someone please remove the post that this question has been answered. This will just frustrate others trying to fine an answer to this problem as I have been for days now. Again if anyone does have a working code to answer this question please post it so this problem can get resolved for others STILL NEEDING A REAL WORKING ANSWER!
//////////////////////////////////////////////////////////////////////////////
EUREKA! “I found it” or at least learned how to write the code.
This is A REAL WORKING ANSWER! , The Blowfish login code I wish I had days ago, when I sill had hair!
The "$2y$" is better for PHP 5.3.7 or higher but I must use the "$2a$" algorithm for PHP 5.3 as explained below from http://php.net/manual/en/function.crypt.php.
Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".
<?php
// Blowfish login code to verify user login password with the hashed password in database
// Make variables from login form on another page and use “include()” to get this PHP code
$user_name_from_login = $_POST[ 'login_user_name' ];
$user_password_from_login = $_POST[ 'login_password' ];
//Check users name for match in your database table of user names
// You must use a line like this “include(‘your_conection_name.php');”
//at the top of your page to get the database connection code or add it directly to this page for this to work
$sql = "SELECT * FROM customers WHERE user_name=:login_user_name";
$query = $db->prepare( $sql );
$query->execute( array( ':login_user_name'=>$user_name_from_login ) );
$results = $query->fetchAll( PDO::FETCH_ASSOC );
//Get hashed password in database associated with user name and make it into a php variable
foreach( $results as $row ){
$database_password_hash = $row[ 'password' ];
}
//Using the Blowfish “$2a$” algorithm with a cost of “11$” and random salt form registration page
// this one line converts login password to the original saved hashed so it can be compared with the one saved in database
$user_password_rehashed = crypt($user_password_from_login, $database_password_hash);
//Now a simple comparison can be made and verified with an “if else” using the variables above
if
($user_password_rehashed == $database_password_hash) {
echo '<br>';
echo ' User’s login password “IS A MATCH” with the one in database (:';
echo '<br>';
}
else
{
echo '<br>';
echo ' User’s login password “DOES NOT MATCH” with the one in database ):';
echo '<br>';
}
//Check your output to better understand process
echo '<br>';
echo ' $user_password_from_login = ' . $user_password_from_login;
echo '<br>';
echo ' $user_password_rehashed --- = ' . $user_password_rehashed;
echo '<br>';
echo ' $database_password_hash --- = ' . $database_password_hash;
echo '<br>';
?>
I hope this will save time and money for other web designers…
I know it would be better to use PHP 5.5 with password hash () and password verify() but PHP 5.3 doesn’t seem to recognize them…
Use the password_compat library. It provides those functions for PHP 5.3.7 and later.
The problem with your better_crypt() function is that it generates a new random salt every time it is called, so the results can't be verified. To be compatible with crypt(), it would need to take a salt from another password hash as input.
But don't do that. Use password_compat.

Auto Login from email link and PHP?

I'm trying to create a link that when clicked will login a user automatically and take them to a specific page.
I've thought about creating some sort of hashed string that contains the user's ID, username and a few other pieces of info. When clicked these pieces of information are looked up in the DB and if validated I login them in and redirect them to a specific page.
For sites like Twitter and Facebook when I receive an email notification and click the link in my email I'm automatically taken to my inbox on the corresponding site. I'm trying to duplicate that behavior...
Are there any security issues with doing something like this or is there a safer more preferred way?
if you want to offer this feature to your users, you have to take care of two things:
The validity of the created url must be set in time (ex: 24hours, 48hours).
The created url must only work for one specific user.
(optionnal) The created url only work for one page
I propose this kind of solution to create an url which match these criteria (it's only a proof of concept):
<?php
$privateKey = 'somethingVerySecret';
$userName = 'cedric';
$url = 'my/personal/url';
$timeLimit = new DateTime('Tomorow');
function createToken($privateKey, $url, $userName, $timeLimit){
return hash('sha256', $privateKey.$url.$userName.$timeLimit);
}
function createUrl($privateKey, $url, $userName, $timeLimit){
$hash = createToken($privateKey, $url, $userName, $timeLimit->getTimestamp());
$autoLoginUrl = http_build_query(array(
'name' => $userName,
'timeLimit' => $timeLimit,
'token' => $hash
));
return $url.'?'.$autoLoginUrl;
}
function checkUrl($privateKey){
if((int)$_GET['timeLimit'] > time() ){
return false;
}
//check the user credentials (he exists, he have right on this page)
$hash = createToken($privateKey, $_SERVER['PHP_SELF'], $_GET['name'], $_GET['timeLimit']);
return ($_GET['token'] == $hash);
}
The general standard for logging in is when a user creates an account your program should create a string of seemly random letters and numbers with a certain php function in php 5.5, and then store this in a file with some sort of pointer based on the username. Then when a user tries to login you use that same function and compare the two strings. The function being hash_pbkdf2 even though this php function supports sha... encryptions do not use those. I salt the hash code with the username. Here is an article on all website login and password things. The most secure thing you can do with your website to prevent people from brute force cracking your passwords is to limit the connection speed after a couple wrong password attempt to something so slow it would take longer than the life of the universe to crack after a couple password attempts. If you wanted to make a sort of remember me button store the username in cookies But never the password the browser will take care of the remembering password part if you label your form elements correctly.

PHP secure logon script - md5 hash is not matching the hash i wrote to the database in a previous script?

I am trying to cobble together a login script in PHP as a learning project.
This is the code for my database write when the user registers. Both of these values are written to the database.
$this->salt = md5(uniqid());
$this->password = md5($password.$salt);
Upon logging in, the following function is fired.
function challengeLogin($submittedPassword, $publicSalt, $storedPassword){
if(md5($submittedPassword.$publicSalt) == $actualPassword){
return 0;
}else{
return 1;
};
}
Unfortunately, on stepping through my code, the two values have never equaled. Can someone help me understand why?
I think the problem in your code is that the $salt variable is undefined, so it is empty. You should use $this->salt
Change
$this->password = md5($password.$salt);
to
$this->password = md5($password.$this->salt);
Compare the raw values before it gets hashed with some basic echo statements. Either the salt is wrong, your password is wrong, or the hash somehow got screwed up.

Categories