Thursday 4 October 2018

Data Encryption and Decryption In CodeIgniter

Data Encryption and Decryption In CodeIgniter - 1



Data Encryption and Decryption In CodeIgniter - 2



Data Encryption and Decryption In CodeIgniter - 3




Do you know what is data encryption and decryption in Web development, so we have explain you data encryption and decryption is to convert plain text into random alphanumeric with special character and that string has no any meaning. So when data store into Mysql database then it has been encrypted and when that data we want see on web page then that will be converted into plain string format in it's original meaning.

Most of web developers has used data encryption for store their highly secured data like password, credit card number OTP etc. Because this type of data is very important, so if someone has hack this data then he can misuse this type data. For this we have to store this type of data in encryption form, so if someone has hack our data then he cannot use this type of data because it has been store in encrytion form and it this can be decrypted by using encryption key which has been used for decrypt this data.

If you have used Codeigniter framework for your web development, then data encryption and decryption will be much easier than using simple PHP script. Because Codeigniter has it's own encryption library for encrypt and decrypt data. You has to just load library and use that library function then data will be easily encrypted and decrypted.

Now one question aris in your mind how can we load Codeigniter encryption library, for this you have to write following code, this code will load encryption library in your code environment.


<?php

$this->load->library('encrypt');

?>







Once this library has been load then by using this encrypt library object we can access different method of data encryption and decryption of this library by using this $this->encrypt. Before using this library in our working code for data encrypt and decrypt, first we have to set the encryption key in our Codeigniter framework. This key is used by different library and helper of Codeigniter like Session, Encrypt etc. By using this key it has cryptographic process and based on this key it has encrypt and decrypt data. That means data will be plain text to encrypted form by using key and from encryted form to plain text by using this encryption key. So, once you has define this key then after you do not change this key otherwise your encrypted data will be lost.

This is simple key in which we can use random character with alphanumeric and not plain string and it must be 32 characters long. For define this encryption key we have go to application/config/config.php file. In this file you have to file below code and define your encryption key.


<?php

$config['encryption_key'] = "YOUR KEY"; 

?>


After define your encryption key in your Codeigniter framwork, now we can use Encrypt library of Codeigniter for data encryption and decryption. For convert plain text to encrypted string we can use following method of encrypt library of Codeigniter.


<?php

$this->encrypt->encode()

?>


Once data has been encrypted and store in database, now again we want to convert into plain text form. For this we can use following method of Encrypt library of Codeigniter.


<?php

$this->encrypt->decode();

?>


Now you want to learn how can we use this encrypt library for data encryption and decryption in real example, so below we have make simple example of Codeigniter Crud, in which we have define step by step how data will be encrypted when it has been insert into Mysql data. That means we have define How can we insert encrypted data into Mysql database by using Codeigniter Encrypt Library.

Once encypted data has been store into Mysql database, now we want to display encrypted data on web page in plain text form. So by using Codeigniter Encrypt library we have define how can we fetch encrypted data from Mysql database and display on web page in plain text form in tabular format. Here we have also define how can we Codeigniter Encrypt library for edit or update encrypted data. Below you can find complete source code code for Insert Update and Fetch encyrption and decryption data in Codeigniter.

Database


Following script will help you to make table in your Mysql database.







--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` text NOT NULL,
  `last_name` text NOT NULL,
  `age` text NOT NULL,
  `gender` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;


Controllers - EncryptionDecryption.php


This is controllers source code, in which you can find code for Insert data, Fetch data and Update data. How can we have load Encrypt Library and how we have use encode() and decode() method of Encrypt library for data encryption and decryption.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class EncryptionDecryption extends CI_Controller {

 function index()
 {
  $this->load->model('encryptiondecryption_model');
  $this->load->library('encrypt');
  $data['data'] = $this->encryptiondecryption_model->fetch_data();
  $this->load->view('encryption_decryption', $data);
 }
 
 function insert()
 {
  $this->load->view('insert_data');
 }

 function insert_validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
  $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
  $this->form_validation->set_rules('age', 'Age', 'required|numeric|trim');
  $this->form_validation->set_rules('gender', 'Gender', 'required|trim');
  if($this->form_validation->run() == false)
  {
   $this->insert();
  }
  else
  {
   $this->load->library('encrypt');

   $data = array(
    'first_name' => $this->encrypt->encode($this->input->post('first_name')),
    'last_name'  => $this->encrypt->encode($this->input->post('last_name')),
    'age'   => $this->encrypt->encode($this->input->post('age')),
    'gender'  => $this->encrypt->encode($this->input->post('gender')),
   );
   $this->load->model('encryptiondecryption_model');
   $this->encryptiondecryption_model->insert($data);
   $this->session->set_flashdata('action', 'Data Inserted');
   redirect('encryptiondecryption');
  }
 }

 function edit()
 {
  $this->load->library('encrypt');
  $this->load->model('encryptiondecryption_model');
  $data['data'] = $this->encryptiondecryption_model->fetch_single_data($this->uri->segment(3));
  $this->load->view('edit_data', $data);
 }

 function edit_validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
  $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
  $this->form_validation->set_rules('age', 'Age', 'required|numeric|trim');
  $this->form_validation->set_rules('gender', 'Gender', 'required|trim');
  if($this->form_validation->run() == false)
  {
   $this->edit();
  }
  else
  {
   $this->load->library('encrypt');

   $data = array(
    'first_name' => $this->encrypt->encode($this->input->post('first_name')),
    'last_name'  => $this->encrypt->encode($this->input->post('last_name')),
    'age'   => $this->encrypt->encode($this->input->post('age')),
    'gender'  => $this->encrypt->encode($this->input->post('gender')),
   );
   $this->load->model('encryptiondecryption_model');

   $this->encryptiondecryption_model->edit($this->input->post('hidden_id'), $data);

   $this->session->set_flashdata('action', 'Data Updated');
   redirect('encryptiondecryption');
  }
 }
 
}

?>


Models - EncryptionDecryption_model.php


This is Mysql database side operation code for Insert data into Mysql table, fetch single data and select all data from Mysql table and update or edit data option.


<?php
class EncryptionDecryption_model extends CI_Model
{
 function insert($data)
 {
  $this->db->insert('sample_data', $data);
 }

 function fetch_data()
 {
  $this->db->order_by('id', 'DESC');
  $query = $this->db->get('sample_data');
  return $query;
 }

 function fetch_single_data($id)
 {
  $this->db->where('id', $id);
  return $this->db->get('sample_data');
 }

 function edit($id, $data)
 {
  $this->db->where('id', $id);
  $this->db->update('sample_data', $data);
 }
}

?>


Views - insert_data.php


This is views file source code and below file will display insert data form on web page page and this page has been load by insert() method of Controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Insert Data</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <style>
    body
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 600px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Insert Data</h3>
   <br />
            <?php
            if(validation_errors() != '')
            {
                echo '
                <div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    ' . validation_errors() .'
                </div>
                ';
            }
            ?>
   <form method="post" action="<?php echo base_url(); ?>encryptiondecryption/insert_validation">
                <input type="text" name="first_name" class="form-control" placeholder="Enter First Name" />
                <br />
                <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name" />
                <br />
                <input type="text" name="age" class="form-control" placeholder="Enter Age" />
                <br />
                <select name="gender" class="form-control">
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <br />
                <div align="center">
                    <input type="submit" name="insert" class="btn btn-primary" value="Insert" />
                </div>
            </form>
  </div>
  <br />
 </div>
</body>
</html>


Views - encyption_decryption.php


This view file will display all mysql data in plain text form on web page in tabular format with edit button link and this file has been load by using index() method of Controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Fetch Data</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <style>
    body
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 800px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Fetch Data</h3>
   <br />
   <div class="table-responsive">
   <?php
   if($this->session->flashdata('action'))
   {
    echo '
    <div class="alert alert-success alert-dismissible">
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      '.$this->session->flashdata('action').'
     </div>
    ';
   }
   ?>
    <div align="right">
     <a href="<?php echo base_url(); ?>encryptiondecryption/insert" class="btn btn-primary btn-sm">Add</a>
    </div>
    <br />
    <table class="table table-striped table-bordered">
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
      <th>Gender</th>
      <th>Edit</th>
     </tr>
     <?php
     foreach($data->result() as $row)
     {
      echo '
      <tr>
       <td>'.$this->encrypt->decode($row->first_name).'</td>
       <td>'.$this->encrypt->decode($row->last_name).'</td>
       <td>'.$this->encrypt->decode($row->age).'</td>
       <td>'.$this->encrypt->decode($row->gender).'</td>
       <td><a href="'.base_url().'encryptiondecryption/edit/'.$row->id.'">Edit</a></td>
      </tr>
      ';
     }
     ?>
    </table>
   </div>
  </div>
  <br />
 </div>
</body>
</html>


Views - edit_data.php


This views files has been used for edit or update data, it will load form with filled data for update and this file has been load by using edit() method of controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Update Data</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <style>
    body
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 600px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Update Data</h3>
   <br />
   <?php

            foreach($data->result() as $row)
            {
            ?>
            <script>
            $(document).ready(function(){
                $('#gender').val("<?php echo $this->encrypt->decode($row->gender); ?>");
            });
            </script>
            <form method="post" action="<?php echo base_url(); ?>encryptiondecryption/edit_validation">
                <input type="text" name="first_name" class="form-control" placeholder="Enter First Name" value="<?php echo $this->encrypt->decode($row->first_name); ?>" />
                <br />
                <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name" value="<?php echo $this->encrypt->decode($row->last_name);?>" />
                <br />
                <input type="text" name="age" class="form-control" placeholder="Enter Age" value="<?php echo $this->encrypt->decode($row->age); ?>" />
                <br />
                <select name="gender" id="gender" class="form-control">
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <br />
                <div align="center">
                    <input type="hidden" name="hidden_id" value="<?php echo $row->id; ?>" />
                    <input type="submit" name="insert" class="btn btn-primary" value="Edit" />
                </div>
            </form>
            <?php
            }

            ?>
  </div>
  <br />
 </div>
</body>
</html>


If you want to download complete file of this Insert Update and Fetch encrypted and decrypted data in Codeigniter tutorial, then you can download complete source code file by click on below download link.




4 comments:

  1. ola o arquivo winrar esta corronpido

    ReplyDelete
  2. Hi i'm using datatables in my software so how to add encrypt

    ReplyDelete
  3. We need shorting and filter features in grid so is it possible using CI encryption??

    ReplyDelete
  4. how to use search / filter SQL in encrypt / decrypt

    ReplyDelete