Search code examples
phpaccess-tokenmcrypt

mcrypt decode data type


I have PHP code for mcrypt to encode and decode an access token as shown below:

$string = "secrettoken";

// Encryption/decryption key
$key = "key12345";

// Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_256;

// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, 
    MCRYPT_MODE_ECB), MCRYPT_RAND);

// Output original string
print "Original string: $string <p>";

// Encrypt $string
$encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_CBC, $iv);
$token = bin2hex($encrypted_string); //prints in hexadecimal format

// Convert to hexadecimal and output to browser
print "Encrypted string: ".encrypted_string."<p>";

$decrypted_string = mcrypt_decrypt($cipher_alg, $key, $encrypted_string,  
    MCRYPT_MODE_CBC,$iv);

print "Decrypted string: $decrypted_string";

//check if the original string is equal to the descripted string
if($decrypted_string == $string)
    print("Yep");
else 
print("Nada");

//After running the scrypt, i get the following results: Original string: secrettoken Encrypted string: encrypted_string Decrypted string: secrettoken String=Decrypted string: False

So it seems like even though the value of $string and $descrypted-string are the same, trying to compare the values proves they are not. I am assuming it has to do with the data types. I have to confess that i am just learning PHP (My main platform is Java and there variable types are declared unlike PHP). So how can i compare the two values to get true? I tried using "===" and also did not work.


Solution

  • I've run this locally, and the var_dump of each variable shows that your decrypted variable has some characters on the end (��������������������).

    Adding a simple trim() to remove whitespace and new lines etc to this variable produces an identical match with strict comparison (===).

    if(trim($decrypted_string) === $string)
        print("Yep");
    

    For reference (because you said you're new to PHP), var_dump($var_name) is a great way to compare variables because it outputs the variable type as well as the value and any whitespace etc on either end.

    Loose comparison == doesn't take variable types into account, so e.g. '123' == 123 is true. Strict comparison === does take types into account, so e.g. '123' === 123 is false. In my opinion, strict comparison should be used wherever possible if you are expecting variables to be a certain type, because with loose comparison boolean true can == 1, or even 0. There can be some unexpected results sometimes as PHP shuffles variable types to suit itself...