Home >>PHP Object Oriented >Encrypt and Decrypt String in PHP
In this tutorial We are going to create a Jumbler Class which allows users to encrypt and decrypt text using a simple encryption algorithm and a user-supplied numeric key.
Take a look a the class Definition (jumbler.php)
<?php //calss definition class jumbler { //define public properties key public $key; //define a method to set encrtyption key public function setKey($key) { $this->key=$key; } //define a method to get encrtyption key public function getKey() { return $this->key; } //define a method to encrypt a string public function encrypt($plainText) { for($x=0;$xgetkey()+($x*$this->getkey()); } return implode("/",$cipher); } //define a method to decrypt a string public function decrypt($cipher) { $data=explode("/",$cipher); $plainText=''; for($x=0;$x getkey()-($x*$this->getkey())); } return $plainText; } } ?>
<?php //call submit button extract($_REQUEST); if(isset($submit)) { $obj= new jumbler(); $obj->setKey($key); if($chk=="C") { echo $obj->decrypt($text); } else { echo $obj->encrypt($text); } } ?> <!DOCTYPE html> <html> <head> <title>Encrypting and Decrypting Text</title> </head> <body> <form method="post"> <table> <tr> <td>Select Your Choice</td> <td> <input type="radio" name="chk" value="P">Encrypt <input type="radio" name="chk" value="C">Decrypt </td> </tr> <tr> <td>Enter Your Data</td> <td><textarea rows="6" name="text" cols="25"></textarea></td> </tr> <tr> <td>Enter Numeric Key</td> <td><input type="number" name="key"></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="submit" value="submitt"> </td> </tr> </table> </from> </body> </html>
Explanation :
This class has a single Property and four methods:
A Quick word about the internal of the encrypt( ) and decrypt( ) methods, before proceeding to a usage example . When encrypt( ) is invoked with a plain-text string, it steps through the string and calculates a numeric value of each character. The numeric value is the sum of
Each number returned after this calculation is added to an array, and once the entire string is processed, the elements of the array are joined into a single string, separated by slashes, with implode( ).