PHP Encryption and Decryption
From w3cyberlearnings
Contents |
Encryption and Decryption
- Encryption makes string to unreadable.
- Decryption makes the unreadable string to readable.
- Information such as email, password, database connection string, and sensitive data can be encrypted
PHP class for encryption and decryption (Encryption.php)
- This class allow you to encrypt and decrypt your information
- This class use the $key to generate encryption and decryption accordingly.
- The Encryption class declared two static functions called encrypt and decrypt functions.
- The encrypt function uses to encrypt, and the decrypt function is for decryption.
<?php class Encryption { private static $key = "I@Love#2001$$$"; public static function encrypt($string) { $key = Encryption::$key; $result = ""; for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key)) - 1, 1); $char = chr(ord($char) + ord($keychar)); $result.= $char; } return base64_encode($result); } public static function decrypt($string) { $key = Encryption::$key; $result = ""; $string = base64_decode($string); for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, ($i % strlen($key)) - 1, 1); $char = chr(ord($char) - ord($keychar)); $result.=$char; } return $result; } } // assign password $password = 'so$sc32dcda'; // generate encryption password $password_encrypt = Encryption::encrypt($password); // decryption the encrypted password $password_decrypt = Encryption::decrypt($password_encrypt); // display result echo 'Password: ' . $password . "<br/>"; echo 'Encryption password: '. $password_encrypt . "<br/>"; echo 'Decryption password: '. $password_decrypt . "<br/>"; ?>
Display Result
Password: so$sc32dcda Encryption password: l7hkv9Kpl4eVlJE= Decryption password: so$sc32dcda How to connect to MySQL with this function
Usage
- Encrypt and decrypt the MySQL database authentication information.
- Prevent security risk by hiding all the information from user.
<?php require_once 'Encryption.php'; // the connection string is already encrypted // we use Encryption::encrypt($variable) to encrypt the host, user, and password $host = 'kLijrdve1Jam'; $user = 'lrivwA=='; $pass = 'h6qvttjX04o='; // connect to mysql server $connection= mysql_connect (Encryption::decrypt($host), Encryption::decrypt($user), Encryption::decrypt($pass)) or die("Unable to connect to the MySQL Server!"); // check connect if (!$connection) { die ("A connection to the MySQL could not be established!"); } else { echo "Connect to MySQL is successful!"; } // close connection mysql_close($connection); ?>
You can create your own encryption by using the PHP str_replace() function
- Use PHP str_replace() function for encrypt and decrypt.
- You need to create two arrays that are equaled in size in order to use this method.
- This method is very unique and easy to implement
Code (str_string_reen.php)
<?php $code = array('^#','^!','`"','(*',',.','#*','*(','}|','*,','&^', '@~','.[','+=','+(','%$','\*','`-','<|','-+','!*', ';~',',[',',&','; ',';:'); $character_input = array('a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r', 's','t','u','w','x','y','z'); $password = 'password'; $encrypt = str_replace($character_input, $code, $password); $decrypt = str_replace($code, $character_input, $encrypt); echo 'Encrypt: '. $encrypt . "<br/>"; echo 'Decrypt: '. $decrypt . "<br/>"; ?>
Display Result
Encrypt: \*^#-+-+,[%$<|(* Decrypt: password
Secure your password by using md5
- Use md5 to encrypt function to encrypt password before we insert it into the database.
Code (register.html)
- This is the Register.html for the HTML form.
<html> <head> <title>Create Account</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form action="register.php" method="post"> <p> <label for='loginEmail'>Login Email</label> <input type='text' name='loginEmail' id='loginEmail'/> </p> <p><label for='password'>Password</label> <input type='password' name='password' id='password'/> </p> <p> <input type="submit" name="submit" value="Create Account"/> </p> </form> </body> </html>
Code (register.php)
- Encrypt user email address and password, and insert them into the database.
- Combine user email and password and encrypt them together before insert into the table.
<?php // import encrytion class require_once 'Encryption.php'; // we encrypted mysql login information $host = 'kLijrdve1Jam'; $user = 'lrivwA=='; $pass = 'h6qvttjX04o='; $db = 'l6you97i'; // connect to mysql server $connection= mysql_connect ( Encryption::decrypt($host), Encryption::decrypt($user), Encryption::decrypt($pass)) or die("Unable to connect to the MySQL Server!"); mysql_select_db(Encryption::decrypt($db)); // encrypt by combine user email and password $loginEmail = strip_tags(substr($_POST['loginEmail'],0,32)); $loginPassword = strip_tags(substr($_POST['password'],0,32)); $secret_password = crypt(md5($loginEmail),md5($loginPassword)); $register_new = 'INSERT INTO user(loginEmail,password) VALUES("' . $loginEmail .'","' . $secret_password .'")'; if(!mysql_query($register_new, $connection)) { die ("Error create a new user". mysql_error()); } else { echo "Successfully create a new user"; } //close connection mysql_close(); ?>
Login and Check MySQL Database
- From the previous example, we insert login email and password into the MySQL database.
- In this tutorial, we do the opposite. Decrypt the user information and compare them in the database.
Code (login.html) HTML login page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Login</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form action="login.php" method="post"> <p><label for='loginEmail'>Login Email</label> <input type='text' name='loginEmail' id='loginEmail'/> </p> <p><label for='password'>Password</label> <input type='password' name='password' id='password'/> </p> <p> <input type="submit" name="submit" value="Log in"/> </p> </form> </body> </html>
Code (login.php)
- login.php check the user email address and password in MySQL database.
- We use the same encryption method from the previous tutorial.
<?php // import encryption class require_once 'encryption.php'; // we encrypted mysql information for security purpose $host = 'kLijrdve1Jam'; $user = 'lrivwA=='; $pass = 'h6qvttjX04o='; $db = 'l6you97i'; // connect to mysql server $connection= mysql_connect (Encryption::decrypt($host), Encryption::decrypt($user), Encryption::decrypt($pass)) or die("Unable to connect to the MySQL Server!"); mysql_select_db(Encryption::decrypt($db)); $loginEmail = strip_tags(substr($_POST['loginEmail'],0,32)); $loginPassword = strip_tags(substr($_POST['password'],0,32)); // we encrypted password $secret_password = crypt(md5($loginEmail),md5($loginPassword)); $sql_query = 'SELECT user_id, loginEmail FROM user WHERE loginEmail="'. mysql_real_escape_string($loginEmail).'" AND password="'. mysql_real_escape_string($secret_password). '" LIMIT 1'; $result = mysql_query($sql_query); if (mysql_num_rows($result)){ //password and login email are matched echo "Successful login <br/>"; $data = mysql_fetch_assoc($result); echo $data['user_id']. ' '. $data['loginEmail']; } else{ //no match echo "Unsuccessful login <br/>"; } ?>