Search code examples
phpmcrypt

Check result of mcrypt_encrypt


I used MCRYPT_ENCRYPT and this method:

class Encrypter {
    private static $Key = "dublin";
    public static function encrypt ($input) {
        $output = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, 
                                md5(Encrypter::$Key), $input, MCRYPT_MODE_CBC,
                                md5(md5(Encrypter::$Key))));
        return $output;
    }

    public static function decrypt ($input) {
        $output = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5(Encrypter::$Key),
                        base64_decode($input), MCRYPT_MODE_CBC, 
                        md5(md5(Encrypter::$Key))), "\0");
        return $output;
    }

}

But I need to perform a check of the result to decrypt.

Is it possible? How?

Thanks!


Solution

  • From what I understand, you want to know how to use your class for checking decryption result. If so, the class can be used like this:

    $originalMessage = 'The quick brown fox jumps over the lazy dog';
    $encryptedMessage = Encrypter::encrypt($originalMessage);
    $decryptedMessage = Encrypter::decrypt($encryptedMessage);
    
    echo $encryptedMessage . PHP_EOL; //prints encrypted message
    echo $decryptedMessage . PHP_EOL; //prints decrypted message
    
    //checks if decrypted message is the same as original
    var_dump($decryptedMessage == $originalMessage);
    

    This will print:

    2tysbFwsmf2YKOBzgafJuHk66zuPjVp8g9E7bsSkPOIBTHlq0SKMeTNbd+/HzxoponxD5eyppxWmUAflJJjM4A==
    The quick brown fox jumps over the lazy dog
    bool(true)
    

    First line is encrypted message,
    second line is decrypted message,
    last line is boolean that indicates whether decrypted message is the same as original one.