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 file function...

If file exists then delete the file. function delFile( $file_name ) { if ( file_exists( $file_name ) ) // Does '$file_name' exist { unlink( $file_name ); return true; } ...

Number Format...

Format a number with grouped thousands......

How to created mixed arguments function...

This way useful for create mixed arguments function. function foo() { $args = func_get_args(); print_r($args); }   foo(1, 1256, 6, 17); //mixed ...   -------------------Out-...

Parse a string into separate words...

Parse a string into separate words (array output). function parser($str, $char = ' ') { $str = trim($str); $str = $str . $char; $len = strlen($str); $words = array(); $w = '...