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

Email Address Checker...

This function check if an e-mail address is valid or not. function valid_email($email) { return preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/', $email);...

Detect file extension function...

This function is used to find the file extension also you can use pathinfo() function for get information about a file path. function ext($file_name) { return substr($file_name, strrpos($fi...

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

SQL escape string function...

Escapes special characters in a string for use in an SQL statement. howewer it check get_magic_quotes_gpc function is enable or no. if true , it strips string from slashes and escaped string from spec...