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

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

Validate phone number...

Chek if a phone numbers is valid, according to its syntax (should be: "+390523599314"). True if it's valid, False otherwise function is_valid_phone( $phone ) { if ( $phone[0] != "+" ) { ...

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

Better parse_str in php...

parse_str() is fine for simple stuff but it's not the same as PHP's built way of creating the $_GET magic variable. Why?!?......