Search code examples
cakephpencryptioncakephp-2.0cakephp-2.1encryption-asymmetric

cakephp : how can i store a encrypted data into db and then decrypt it through key


i am working on a Cakephp 2.3 I'm trying to encrypt my data which i am storing into db, so I searched for a way to do this. I found this http://bakery.cakephp.org/articles/utoxin/2009/08/01/cryptable-behaviore

i dont know its the best behviour or not or if some one has the better behavior then please suggest me ..

so the problem here is i have read all the details in the link but still i cant get to know that how can i save my fields encrypted into db

for example i have a function in controller which is saving data

  $this->Messages->save($this->request->data);

how can i save this data in encrypted in db

and then my modal

 public function getAllMessages($id){

    return  $this->find('all',array(
        'order'=> array( 'idTextMessage DESC'),
        'conditions' => array('User_id' => $id)));
}

how can i decrypt this data

i have done this but didnt work

class Message extends AppModel{
public $useTable = 'textmessage';

public $actsAs = array( 
    'Cryptable' => array( 

        'fields' => array( 
            'mobileNo',
             'body' 
        ) 
    ) 
);

Solution

  • I haven't used that plugin, but it's from 2009, so it's pretty old now. I wouldn't put too much faith in it.

    It's easy to decrypt/encrypt using Cake's Security::rijndael, without using a plugin (note that the mcrypt php extension will need to be installed - but it may well be installed already).

    First, in your model, add an array of the fields you want encrypted:

    public $encryptedFields = array('mobile', 'body');
    

    Then, implement a beforeSave like this:

    public function beforeSave($options = array()) {
        foreach($this->encryptedFields as $fieldName){
            if(!empty($this->data[$this->alias][$fieldName])){
                $this->data[$this->alias][$fieldName] = Security::rijndael($this->data[$this->alias][$fieldName], Configure::read('Security.key'), 'encrypt');
            }
        }
        return true;
    }
    

    Your afterFind method should be pretty much the same, except it should decrypt rather than encrypt:

    public function afterFind($results = array()) {
        foreach($this->encryptedFields as $fieldName){
            if(!empty($results[$this->alias][$fieldName])){
                $results[$this->alias][$fieldName] = Security::rijndael($results[$this->alias][$fieldName], Configure::read('Security.key'), 'decrypt');
            }
        }
        return $results;
    }
    

    Note I haven't tested all of that code - it's hacked together from bits and pieces in one of my own apps. But it should put you on the right track.