Encrypt and Decrypt function with different outputs

Encrypt function return different value with each execute but decrypt function return input value. for example: 

  • first execute: encrypt('hello')       => 'axxdfg34', decrypt('axxdfg34') return 'hello'
  • second execute: encrypt('hello') => 'xvcfghty214s', decrypt('xvcfghty214s') return 'hello'
function get_rnd_iv( $iv_len )
{
   $iv = '';
   while ( $iv_len-- > 0 )
      $iv .= chr( mt_rand() & 0xFF );
   return $iv;
}
 
function encrypt( $plain_text, $password = 'ASXDCFVGED$%kdknddbdFGt123', $iv_len = 5 )
{
   $plain_text .= "";
   $n = strlen( $plain_text );
   if ( $n % 16 )
      $plain_text .= str_repeat( "", 16 - ( $n % 16 ) );
   $i = 0;
   $enc_text = get_rnd_iv( $iv_len );
   $iv = substr( $password ^ $enc_text, 0, 512 );
   while ( $i < $n ) {
      $block = substr( $plain_text, $i, 16 ) ^ pack( 'H*', md5( $iv ) );
      $enc_text .= $block;
      $iv = substr( $block . $iv, 0, 512 ) ^ $password;
      $i += 16;
   }
   $enc_text = base64_encode( $enc_text );
   return $enc_text;
}
 
function decrypt( $enc_text, $password = 'ASXDCFVGED$%kdknddbdFGt123', $iv_len = 5 )
{
   $enc_text = base64_decode( $enc_text );
   $n = strlen( $enc_text );
   $i = $iv_len;
   $plain_text = '';
   $iv = substr( $password ^ substr( $enc_text, 0, $iv_len ), 0, 512 );
   while ( $i < $n ) {
      $block = substr( $enc_text, $i, 16 );
      $plain_text .= $block ^ pack( 'H*', md5( $iv ) );
      $iv = substr( $block . $iv, 0, 512 ) ^ $password;
      $i += 16;
   }
   return preg_replace( '/\x13\x00*$/', '', $plain_text );
}
 
echo $result = encrypt( 'Test' );
echo decrypt( $result );

Tags

No tag here.

Recommended pages

Delete or Remove all files and folders in a directory‎...

If you want to delete everything from folder (including subfolders) use this function. function removeDir( $dir ) { if ( is_dir( $dir ) ) { $objects = scandir( $dir ); foreach ( $o...

Get all subsets of array...

If you have a list of items (for example)......

File size calculator...

File size calculator function return file size format into kb, mb or gb. function file_size($size, $out = 'kb', $precision = 2) { switch ($out) { case 'kb': return round($...

Detect leap year...

Detect leap year for gregorian and shamsi date. function gLeapYear($year) { if (($year % 4 == 0) and (($year % 100 != 0) or ($year % 400 == 0))) return true; else return ...