How to save password in md5 in mysql php

Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.

You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?

The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).

So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:

$query="INSERT INTO ptb_users (id,
        user_id,
        first_name,
        last_name,
        email )
        VALUES('NULL',
        'NULL',
        '".$firstname."',
        '".$lastname."',
        '".$email."',
        MD5('"$user_id.$password."')
        )";

(I am assuming that you've properly escaped all those strings earlier in your code)

The MD5 encryption algorithm is still one of the most used in the world, and specially in MySQL tables.
In this tutorial, I’ll show you how it works in a database, and especially how to generate it easily with PHPMyAdmin.

When inserting a new line with PHPMyAdmin, there is a dropdown menu on the left of the field. Pick the MD5 function in the list and enter the value in clear text. It will automatically convert it in MD5 on insertion.

Today, I’ll give you a step-by-step tutorial on how to create a table to store MD5, how to set your MD5 Password and how to manage this in PHP directly.

  • Creating a demo table
  • Insert a new line with PHPMyAdmin
  • Set a MD5 Password in MySQL and/or PHP directly
    • MySQL
    • PHP
      • Create a user in PHP
      • Verify a user and password in PHP
  • Security issues with MD5
    • Why is MD5 not secure?
    • What you can do to improve security?
    • An example with salt in PHP
  • Conclusion

Creating a demo table

Before going further, I’ll create a basic MySQL table to show you how it works.
My table will simply be “users”, with three fields:

  • auto_id – INT(11): I often create a first field like this one. The goal is to have an auto-incremented number for each line (you can check the A_I checkbox on the same line to do the same).
  • login – VARCHAR(32): It’s just an example, you can use an email address or whatever instead. In this basic example, it’ll be a login.
  • password – VARCHAR(32): The one that interest us today. An MD5 hash is composed of 32 hexadecimal characters, so you need to have 32 in length.

Here is the corresponding MySQL query to create the table if you want to try while reading this post:

CREATE TABLE `users` (
  `auto_id` int(11) NOT NULL,
  `login` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL
)

And the result:

How to save password in md5 in mysql php

We are now ready to insert a new line in this table!

How to save password in md5 in mysql php

Ethical Hacking Course
Learn Ethical Hacking From Scratch
Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

More details

Insert a new line with PHPMyAdmin

In PHPMyAdmin, you can insert new lines with a form, you don’t need to type the MySQL query each time. In this part, I’ll show you how to do this, but if you are also interested in the MySQL query, I’ll give it to you just after.

Here is how to set a MD5 password while inserting your values in PHPMyAdmin:

Once done, the lines look like this:

How to save password in md5 in mysql php

The password is correctly encrypted in the field

Set a MD5 Password in MySQL and/or PHP directly

In this part, I’ll show you how to do the same thing directly in MySQL, but also with PHP.
This should be more convenient than PHPMyAdmin to do this automatically.

MySQL

If you followed the previous method with PHPMyAdmin, you may have seen the MySQL query displayed on your screen.
In any case, here is an example:

INSERT INTO users 
(auto_id, login, password) 
VALUES 
(NULL, 'myuser', MD5('clearpassword'));

So, we just add the “MD5()” function to the password in text, and it will insert a line with a MD5 hash.

By the way, the auto_id field is not mandatory, and will be filled automatically even if you don’t set it to “NULL” in the query.
This query will do the same thing for example:

INSERT INTO users 
(login, password) 
VALUES 
('myuser', MD5('clearpassword'));

Once you have the MySQL Query set for your new users, you can click on “SQL” and paste it directly in PHPMyAdmin.
You can find the MySQL documentation here if you have any specific thing to handle. But for my basic table, it’s enough 🙂

PHP

You now know almost everything, the only step missing is how to check the used password is correct on sign in.
I’ll show you with PHP as it’s the most used language for MySQL, but you can find similar functions in other languages too.

Create a user in PHP

In PHP, there is a pack of functions, starting by mysqli_* that allow you to work with MySQL database.
In this first example, we’ll see how to insert a new line directly from PHP.

Let’s start immediately with the code sample:

<?php
//Connect to your database
$mysqli = new mysqli("localhost","user","password","db");

//Verify connection
if ($mysqli -> connect_errno) {
   die("Database error: ".$mysqli->connect_error);
}

//Run your query
$mysqli->query("INSERT INTO users 
(login, password) 
VALUES 
('myuser', MD5('clearpassword'))");

//Other operations if needed
?>

Here is a short explanation:

  • The first lines will manage the database connection.
  • The next paragraph is to check that you are correctly connected (or if there is an error we stop here, the credentials are probably wrong).
  • Then, we run the same query as seen in the MySQL section.
  • At the end you can add any other request or PHP code you want to complete your registration. But at this point the MD5 part is already done.

Verify a user and password in PHP

Good, now we have seen how to set a MD5 password in our table, from PHPMyAdmin or directly with PHP.
But how to check that the password entered on login (in clear text) is the same as the one in the database (in MD5)?

The MD5 algorithm is not reversible, so the only way is to encrypt the password typed in the form before trying to match it with the database.
Something like that for example:

<?php
//Start with the MySQL connection as in the previous example

//Get the values from the form submitted
$user = $_POST['username'];
$pass = $_POST['password'];

//Look for a corresponding user
$result = $mysqli->query("SELECT * FROM users WHERE login='".$user."' AND password='".md5($password)."'");

if($result->num_rows) {
   //user match
}
else {
   //error, incorrect user or password
}

It’s a basic example you need to complete, but it should give you an idea on how it works.
And yes, PHP has also a built-in MD5 function, so it’s easy to use (documentation).

Security issues with MD5

If you don’t know, you have to be cautious when you use the MD5 algorithm to store passwords. It’s one of the less secure currently in the world, so if you can it’s better to avoid it.

Why is MD5 not secure?

I already wrote an article on the topic, so I’ll give too many details in here, but in short, there are at least 3 reasons why using MD5 is not a good idea:

  1. Dictionary tables: On MD5Online, there is a database with over 1,150 billions password available. There is a pretty high chance that some of your passwords are available in it. You can try our MD5 decrypter for free here.
  2. Brute force: A brute force attack is a method to find a password by trying millions of possibilities. Components are better and better currently to do this (thanks to the big improvements in GPU computing)
    Here is an illustration from Hive Systems:
    How to save password in md5 in mysql php

    And it’s not just for the MD5 algorithm, is global, whatever the algorithm.
  3. Collisions: With MD5, two words can have the same MD5 hash. So it’s potentially two different passwords that can be used for the same encrypted password. It’s not a good thing in security.

If you want to know more about these reasons, check my post on “Why MD5 is not safe?“.

What you can do to improve security?

You can find more details in the linked post above on how to improve security with several solutions.
But for now, I want to introduce one specific way: adding salt 🙂

A salt is a word you add before and/or after the password to encrypt.
For example, instead of hashing “azerty”, you do it with “md5onlineazerty”
This way, even if your database is hacked, it will be more difficult to find the corresponding password to the hash (this salt is probably not a good example, but just to show you the idea).

When someone tries to sign in, you will do the same thing, you take the password entered the form, and you add the salt before hashing the whole string in MD5.
We’ll see in the last part how to implement this in PHP.

An example with salt in PHP

In PHP, using salt is very similar to what we have already done earlier:

<?php
//Start with the MySQL connection as in the previous example

//Get the values from the form submitted
$salt = "mysaltstring";
$user = $_POST['username'];
$pass = $salt.$_POST['password'];

//Look for a corresponding user
$result = $mysqli->query("SELECT * FROM users WHERE login='".$user."' AND password='".md5($password)."'");

if($result->num_rows) {
   //user match
}
else {
   //error, incorrect user or password
}

The only change in PHP is the concatenation between salt and password (“.”).
It’s the same thing for the registration process

If this process with salt is still complicated for you, feel free to check my post on MD5 Salt here.

Conclusion

That’s it, you now have a good overview on how to use MD5 password in PHPMyAdmin, and also in MySQL and PHP.

I hope this post was useful for you, please share it on your favorite social network or forum! 🙂

How do I find the MD5 password in MySQL?

$salt = 'Vwm'; $password = '123123'; echo md5($salt . md5($password . $salt) . $password);

How encrypt MD5 in PHP?

PHP md5() Function.
Calculate the MD5 hash of the string "Hello": $str = "Hello"; echo md5($str); ?> ... .
Print the result of md5(): $str = "Hello"; echo "The string: ". $str."<br>"; ... .
Print the result of md5() and then test it: $str = "Hello"; echo md5($str); if (md5($str) == "8b1a9953c4611296a827abf8c47804d7").

How do I change my MD5 password?

To do this, find the “MD5” function in the dropdown list..
The “auto_id” needs to stay empty (will be automatically set).
Type the “login” you want to create..
Enter the “password” in clear mode in the value column..

Can we decrypt MD5 in PHP?

How to Decrypt MD5 Passwords in PHP? The MD5 cryptographic algorithm is not reversible i.e. We cannot decrypt a hash value created by the MD5 to get the input back to its original value. So there is no way to decrypt an MD5 password.