Data Encryption in PHP using crypt()
PHP provides you with the crypt() function for one way encryption of data.
For example,if you have a registration form to enter the password and suppose we require it to be secure,that is,to be saved in the database in the encrypted manner,we can use this function.
Basic syntax of the crypt() function is
crypt(your string,salt)
The salt parameter influences how the encryption will work
Mainly 4 types of salts are supported.
Two DES encryption salts
CRYPT_STD_DES(2 character salt)
CRYPT_EXT_DES(9 character salt)
and
CRYPT_MD5(12 character salt,starts with $1$)
CRYPT_BLOWFISH (16 character salt,starts with$2$ or $2a$)
Lets see the working of the crypt() in action
Read Basics about PHP and MySQL first.
Firstly i have create table in database “test”.
Table name=registration
Fields
uid varchar(255)
pwd varchar(255)
I am trying to insert into this table,with the password in the encrypted form.Here is the html form for this.
<html>
<body>
<form action="register.php" method="post">
UserName<input type="text" name="username" />
Password <input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
Note that the form data is sent to register.php by the POST method.
Now lets see the register.php page
<?php
$mycon = mysql_connect("localhost","root","");
if (!$mycon)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $mycon);
$encryptedpwd=crypt($_POST['password'],'d4');
echo $encryptedpwd;
$sql="INSERT INTO Registration(uid,pwd) VALUES ('$_POST[username]','$encryptedpwd')";
if (!mysql_query($sql,$mycon))
{
die('Error: ' . mysql_error());
}
echo "Sucessfully registerd";
mysql_close($mycon)
?>
Note that here i have used a standard DES encryption which has a 2 character salt ‘d4′.
In the registration table,the password will be inserted in the encrypted format.
In the login form,we do the same thing.When crypt() is called,the password entered is encrypted and checked against the already encrypted password to see whether it matches. You will have to use the same salt you used earlier for this to work.
The crypt() using different types of salts
$encryptedpwd=crypt($_POST['password'] , ‘g477d.reg’);
$encryptedpwd=crypt($_POST['password'] , ‘g477d.reg’);
$encryptedpwd=crypt($_POST['password'] , ‘$1$ad235de$’);
$encryptedpwd=crypt($_POST['password'] , ‘$2$dads….$’);
Related posts:








Leave your response!