Make a custom helpers in kohana for encrypt data

First of all, we make a helper file in helper folder under system directory. Suppose my helper name is encryptdata.php then class name must be encryptdata_Core. _Core will be added in class name when you want to use as a helper file.

Script for Custom Helper (Here is encryptdata which is used to encrypt any string):

<?php defined(‘SYSPATH’) OR die(‘No direct access allowed.’);
/**
* Encryptdata helper class.
*
*
* @package    Core
* @author     Ravi Prakash
* @copyright  (c) 2010-2011 Witslog.com
*/
class encryptdata_Core {

var $method     = “”;
var $repeats     = 0;
var $split_crypt     = 0;
var $final_method     = “md5″;
/**

*/

public static function do_encrypt( $data,$method, $final, $repeats=2, $split=0 )
{
// Work out the method.
$var1= new encryptdata_core;
if( is_array($method) )
{
$var1->method = $method;
}
else
{
$var1->method = $method;
}

$var1->repeats = $repeats;
$var1->split_crypt = $split;
$var1->final_method = $final;

if( is_array($var1->method) )
{
if( in_array(’sha1′, $var1->method) )
{
$data = encryptdata::_run_encrypt_function( $data, ’sha1′ );
}
if( in_array(‘md5′, $var1->method) )
{
$data = encryptdata::_run_encrypt_function( $data, ‘md5′ );
}
}
else
{
$data = encryptdata::_run_encrypt_function( $data, $var1->method );
}

// Which method should we use for the final output?
// And should we trim this crypt?

if( $var1->final_method == ‘md5′ )
{
return $var1->split_crypt != 0 ? substr( md5($data), 0, $var1->split_crypt) : md5( $data );
}
else if( $var1->final_method == ’sha1′ )
{
return $var1->split_crypt != 0 ? substr( sha1($data), 0, $var1->split_crypt) : sha1( $data );
}
else
{
return $var1->split_crypt != 0 ? substr( md5($data), 0, $var1->split_crypt) : md5( $data );
}
}

public static function _run_encrypt_function( $data, $func )
{
$var1= new encryptdata_core;
if( !function_exists( $func ) )
{
$func = ‘md5′;
}

if( $var1->repeats > 0 )
{
for( $i = 0; $i < $var1->repeats; $i++ )
{
$data = $func( $data );
}
}
return $data;
}

} // End encryptdata

In helpers file all the functions will be static.

How to call this class in my controller:

To call this file you will simply call function of this class by classname without ‘_core’.  ‘_core’ is internally handle by kohana.

echo encryptdata::do_encrypt(‘ravi prakash’,'md5′, ‘md5′, 2, 0 );

……………………………………………………………………………………………………………..

I hope this article will help you to learn deeply Kohana.

About the Author

admin