Strings no longer equal after encryption and decryption
I use the following class to encrypt and decrypt a string. After creating two identical strings, I encrypt one of the strings and then decrypt it. However, the decrypted string is no longer equal to its twin (even though they look identical in text form after the conversion) . Also, after taking the encrypt-decrypted string and its twin and convert them to hex use bin2hex, I find out that they look similar only that the string that got encrypted before has an addition number of zero at the end.
Can someone point out what I did wrong? Thank you in advance.
class proCrypt {
public function __set( $name, $value )
{
switch( $name)
{
case 'key':
case 'ivs':
case 'iv':
$this->$name = $value;
break;
default:
throw new Exception( "$name cannot be set" );
}
}
/**
*
* Gettor - This is called when an non existant variable is called
*
* @access public
* @param string $name
*
*/
public function __get( $name )
{
switch( $name )
{
case 'key':
return 'abcd';
case 'ivs':
return mcrypt_get_iv_size( MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB );
case 'iv':
return mcrypt_create_iv( $this->ivs );
default:
throw new Exception( "$name cannot be called" );
}
}
/**
*
* Encrypt a string
*
* @access public
* @param string $text
* @return string The encrypted string
*
*/
public function encrypt( $text )
{
// add end of text delimiter
$data = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
return bin2hex($data);
}
/**
*
* Decrypt a string
*
* @access public
* @param string $text
* @return string The decrypted string
*
*/
public function decrypt( $text )
{
$text = pack("H*" , $text);
return mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
}
} // end of class
Encryption algorithms usually require input that is a multiple of some length (8 bytes, 16 bytes, etc) to work with their fixed "block size". Your input string may have gotten 0-padded to match. You could undo it by keeping track of the necessary padding based on your algorithm of choice (each algorithm will have its own block size and padding method), and undo it after the decryption.
You've got a 16-length string padded with spaces, presumably. Try trim() before bin2hex() to get rid of the leading and trailing spaces.
精彩评论