Thread: tutorials
View Single Post
Old 11-15-2004   #8 (permalink)
scrowler
code anyone?
 
scrowler's Avatar
 
Join Date: Feb 2004
Location: New Zealand
Posts: 590

Send a message via MSN to scrowler Send a message via Skype™ to scrowler
md5() encryption using PHP

One of the many ways of encrypting data using PHP is a function called md5().

md5() converts a string of text into a 32-character hash, using a secret algorythm, so as to protect its source. md5() encrypted strings cannot be decrypted. When I first learnt this I thought to myself - "how the heck can I check to see if two md5'd strings are equal then?" and the answer is simple, so simple that it seriously annoyed me. Take a login system for example, instead of decrypting the string and comparing it to a regular password, you take the encrypted string and compare it to a string that has already been encrypted! Simple huh?

So let’s write ourselves a little test script:

<?php
$string = “string to be encrypted”;
$encstring = md5($string);

echo $encstring;
?>

This will produce a 32-character jumble of letters and numbers, which will not be anything like what the original string was. In this instance, the output would be – “fc8de8ee2c43a9ae2f9023f205d960d6”.

To use md5, simple enclose the string in md5( x ); by replacing the x demonstrated with your string name. E.g. md5($stringname);. Yes, it’s that simple!

Yes, you can use this method to protect pages like admin areas and member only pages, but it has limited reliability, I do not recommend using this function to protect administration areas for big businesses or important websites simply because it is not the most secure method, however, it is sufficient for small businesses and personal use by far.

Let’s write a quick login script to demonstrate my point above:

Expect that you have a form, which uses POST and points to login.php, with a field called “username” and a password field called “password”.

<?php

// login.php written by Robbie Averill for BioRUST on 15/11/04 at 8.28 PM

$username = $_POST[‘username’];
$password = $_POST[‘password’];

$encpassword = md5($password);

$checkpw = “fc8de8ee2c43a9ae2f9023f205d960d6”;

if($encpassword === $checkpw){

echo ‘User logged in successfully! Welcome ’.$username.’!’;

} else {

echo ‘Password was wrong!’;

}

?>

In this instance, the encrypted value checks whether the posted password is equal to it (in this case the password would be “string to be encrypted”.

I hope this basic tutorial on md5() encryption has helped you, good luck!

For more information on the md5() function visit the following link:
http://nz2.php.net/manual/en/function.md5.php

Cya,
Robbie Averill
aka scrowler
__________________
BioRUST Tutorials - the birthplace

Last edited by scrowler; 11-15-2004 at 08:22 AM..
scrowler is offline