PHP and MD5 implementation

PHTech

Senior Member
Joined
Aug 21, 2006
Messages
588
Reaction score
0
Location
Witbank
Hi There...

I have found some interesting articles on http://www.dmxzone.com/showDetail.asp?TypeId=26&NewsId=5437 and http://www.phpeasystep.com/phptu/26.html to implement the MD5 password encryption. NOW - I have managed to get it to ENCRYPT the password in the DB, BUT now I am confused where to implement MD5 so that it can read the encrypted passwors...? :confused:

Should I implement it at the LOGIN page where you insert your username and password, OR at the page after the username and password is read in...? I am a bit confused... Below is a copy of my PHP code in the LOGIN page, if someone can help me to de-encrypt / read the encrypted password:

<?php require_once('Connections/conn_Users.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['usrname'])) {
$loginUsername=$_POST['usrname'];
$password=$_POST['pswrd'];
$MM_fldUserAuthorization = "DBAss";
$MM_redirectLoginSuccess = "indexMenu.php";
$MM_redirectLoginFailed = "adminAuthFailed.php";
$MM_redirecttoReferrer = false;
mysql_select_db($database_conn_Users, $conn_Users);

$LoginRS__query=sprintf("SELECT UsrName, Password, DBAss FROM users WHERE UsrName=%s AND Password=%s",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

$LoginRS = mysql_query($LoginRS__query, $conn_Users) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
if ($loginFoundUser) {

$loginStrGroup = mysql_result($LoginRS,0,'DBAss');

//declare two session variables and assign them
$_SESSION['MM_Username'] = $loginUsername;
$_SESSION['MM_UserGroup'] = $loginStrGroup;

if (isset($_SESSION['PrevUrl']) && false) {
$MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
}
header("Location: " . $MM_redirectLoginSuccess );
}
else {
header("Location: ". $MM_redirectLoginFailed );
}
}
?>
 
I have managed to fix my own problem in reply to my post.

BUT for interest sake, what i have done was added the MD5 tag to the authentication of the form element.

ORIGINAL CODE:
$LoginRS__query=sprintf("SELECT UsrName, Password, DBAss FROM users WHERE UsrName=%s AND Password=%s",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

NEW CODE:
$LoginRS__query=sprintf("SELECT UsrName, Password, DBAss FROM users WHERE UsrName=%s AND Password=MD5(%s)",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

Hope this will help for someone who is also stugling with the MD5.

THANX...
 
Personally I don't think that just changing the password to md5 is good enough. If a hacker were to get the md5 hash he could easily decrypt it with a brute force or dictionary attack. It is important to salt your hashes. This is basically where you added some random characters/numbers of a fixed length into the password. This will help to improve your security against dictionary/brute force attacks a lot.
 
Personally I don't think that just changing the password to md5 is good enough. If a hacker were to get the md5 hash he could easily decrypt it with a brute force or dictionary attack. It is important to salt your hashes. This is basically where you added some random characters/numbers of a fixed length into the password. This will help to improve your security against dictionary/brute force attacks a lot.

OK... Thanx for that information... How about would I go implementing the "SALT" technique...?
 
Personally I don't think that just changing the password to md5 is good enough. If a hacker were to get the md5 hash he could easily decrypt it with a brute force or dictionary attack. It is important to salt your hashes. This is basically where you added some random characters/numbers of a fixed length into the password. This will help to improve your security against dictionary/brute force attacks a lot.

Um... You can't decrypt it, per se... What you mean is that you can find out what the original is. And yes, in that case, salting it is the best thing to do. You could even hash it a few times with different salts.
 
OK... Thanx for that information... How about would I go implementing the "SALT" technique...?

$password = "somepasswordstring";
$salted = $password . "somerandomsaltstring";
$hashed = md5($salted);
 
Cool... Thanx for the tips... I would certainly implement it using the "Salt" technique...
 
Anyway, with regards to the original post, the HASHED password (correct terminology... you don't EVER want this hash to be "decrypted") should be stored in the database. Then when a user logs in, you don't compare their provided password with a decrypted version of your stored hash... Rather, you hash their provided password in the same way that you hashed their stored password, then compare.

For example:
Code:
$hashToStore = md5($originalPass . "some salt");
storeInDb($hashToStore);

Now the password is hashed and stored in the database. When someone wants to log in:

Code:
$hashFromLogin = md5($passFromLogin . "some salt");
if ($hashFromLogin == getFromDb($usernameFromLogin)
{
doLoginStuff();
}

Hope this helps
 
Oh, and if you're wondering why "salting" is a good idea, try the following:

  1. Come up with some "password". Generally a common word or password (remember, your users aren't always going to choose good, secure passwords)
  2. Hash your chosen password
  3. Take the hash and google it
  4. There's a pretty good chance that you'll find out what it is
 
OK Cool... But do you implement the salting where the users register the password, or when they LOGIN with the password...?
 
OK Cool... But do you implement the salting where the users register the password, or when they LOGIN with the password...?

Both... You want the password they provide at registration to match the password they provide at login
 
OK... Below is the PHP part of the Registration page that I am working on currently. I will mark the MD5 tags with RED. and IF POSSIBLE, can you guys maybe help me with the implementation of the SALT tech using my code? I am not so good in hand coding.

<?php require_once('../../Connections/conn_Users.php'); ?>
<?php require_once('../../Connections/conn_Users.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
$logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
//to fully log out a visitor we need to clear the session varialbles
$_SESSION['MM_Username'] = NULL;
$_SESSION['MM_UserGroup'] = NULL;
$_SESSION['PrevUrl'] = NULL;
unset($_SESSION['MM_Username']);
unset($_SESSION['MM_UserGroup']);
unset($_SESSION['PrevUrl']);

$logoutGoTo = "../../adminLogoutSuccess.php";
if ($logoutGoTo) {
header("Location: $logoutGoTo");
exit;
}
}
?>
<?php
if (!isset($_SESSION)) {
session_start();
}
$MM_authorizedUsers = "99";
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;

// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && false) {
$isValid = true;
}
}
return $isValid;
}

$MM_restrictGoTo = "../../adminRestricted.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO users (UsrName, Initials1, Surname, COYNo, Department, EmailAdd, OfficePhn, CellPhn, Password, DBAss, DBAddedBy) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, MD5(%s), %s, %s)",
GetSQLValueString($_POST['UsrName'], "text"),
GetSQLValueString($_POST['Initials1'], "text"),
GetSQLValueString($_POST['Surname'], "text"),
GetSQLValueString($_POST['COYNo'], "int"),
GetSQLValueString($_POST['Department'], "text"),
GetSQLValueString($_POST['EmailAdd'], "text"),
GetSQLValueString($_POST['OfficePhn'], "text"),
GetSQLValueString($_POST['CellPhn'], "text"),
GetSQLValueString($_POST['Password'], "text"),
GetSQLValueString($_POST['DBAss'], "int"),
GetSQLValueString($_POST['DBAddedBy'], "text"));

mysql_select_db($database_conn_Users, $conn_Users);
$Result1 = mysql_query($insertSQL, $conn_Users) or die(mysql_error());

$insertGoTo = "adm_AddUsers.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$usrnsrch_rs_USERAUTH = "-1";
if (isset($_SESSION['MM_Username'])) {
$usrnsrch_rs_USERAUTH = $_SESSION['MM_Username'];
}
mysql_select_db($database_conn_Users, $conn_Users);
$query_rs_USERAUTH = sprintf("SELECT users.ID, users.UsrName, users.Surname FROM users WHERE users.UsrName LIKE %s", GetSQLValueString($usrnsrch_rs_USERAUTH, "text"));
$rs_USERAUTH = mysql_query($query_rs_USERAUTH, $conn_Users) or die(mysql_error());
$row_rs_USERAUTH = mysql_fetch_assoc($rs_USERAUTH);
$totalRows_rs_USERAUTH = mysql_num_rows($rs_USERAUTH);

mysql_select_db($database_conn_Users, $conn_Users);
$query_rs_CurrentUsers = "SELECT users.ID, users.UsrName, users.Surname, users.Department, users.EmailAdd, users.OfficePhn FROM users";
$rs_CurrentUsers = mysql_query($query_rs_CurrentUsers, $conn_Users) or die(mysql_error());
$row_rs_CurrentUsers = mysql_fetch_assoc($rs_CurrentUsers);
$totalRows_rs_CurrentUsers = mysql_num_rows($rs_CurrentUsers);
?>

AND THIS IS THE CODE FOR THE LOGIN PAGE:
<?php require_once('Connections/conn_Users.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['usrname'])) {
$loginUsername=$_POST['usrname'];
$password=$_POST['pswrd'];
$MM_fldUserAuthorization = "DBAss";
$MM_redirectLoginSuccess = "indexMenu.php";
$MM_redirectLoginFailed = "adminAuthFailed.php";
$MM_redirecttoReferrer = false;
mysql_select_db($database_conn_Users, $conn_Users);

$LoginRS__query=sprintf("SELECT UsrName, Password, DBAss FROM users WHERE UsrName=%s AND Password=MD5(%s)",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

$LoginRS = mysql_query($LoginRS__query, $conn_Users) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
if ($loginFoundUser) {

$loginStrGroup = mysql_result($LoginRS,0,'DBAss');

//declare two session variables and assign them
$_SESSION['MM_Username'] = $loginUsername;
$_SESSION['MM_UserGroup'] = $loginStrGroup;

if (isset($_SESSION['PrevUrl']) && false) {
$MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
}
header("Location: " . $MM_redirectLoginSuccess );
}
else {
header("Location: ". $MM_redirectLoginFailed );
}
}
?>
 
Not going to lie... I'm not too keen to read through all that...

But once you understand the gist of what we're saying, you should have no problem implementing it wherever you need it.

Usually, when you get the md5 of "hello", you do something like
Code:
$plainTextString = "hello";
$badlyHashedString = md5($plainTextString);

But now, as I mentioned above, taking that hash and dumping it in google will return you what the original string was. This is NOT necessarily because that particular hash is insecure (there HAVE been a few collisions that have been found), but because somewhere on the web, someone has pasted "hello" and its hash, and google has found and indexed it.

Instead, you want to come up with (what you hope will be) a completely original string. So you use a "salt". The salt is just a string that you append to the plain text string to make it unique.

So if Bob's password is "foo", then you would have something like:
Code:
$plainTextString = "foo";
$saltString = "Any random string can go here. This one works just fine.";
$wellHashedString = md5($plainTextString . $saltString);

Now, it's quite unlikely that somewhere in the world, someone has hashed and published the string "fooAny random string can go here. This one works just fine.".

Now you have $wellHashedString which you would store in your database when the person first registers.

Now when they login, they will give you their password (they don't know anything about the salting... That is your little secret). So Bob will give you password "foo", and you will turn "foo" into "fooAny random string can go here. This one works just fine." and hash the NEW string before comparing it to what you have stored in the database.

To take the example further, say BillGates Haxor is trying to crack the password. He'll often start by using a dictionary-type attack. This attack attempts to use a HUGE list of common words and phrases that could be used as passwords. When people choose regular words as passwords, this kind of brute-force attack can be quite effective. But it's quite unlikely that "fooAny random string can go here. This one works just fine." will be in that list.
 
Top
Sign up to the MyBroadband newsletter
X