Search code examples
phpencryptionaesrijndael

Decrypted string is sometimes not same as encrypted source


class Auth extends MySQLi {
public function aes_enc($encrypt, $mc_key, $iv) {
    $passcrypt = trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), trim($encrypt), MCRYPT_MODE_CBC, $iv));
    return $passcrypt;

}

public function aes_dec($decrypt, $mc_key, $iv) {

    $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), trim($decrypt), MCRYPT_MODE_CBC, $iv));
    return $decrypted;

}

public function salt() {
return str_shuffle('abcdefghijklmnoprsquvzyx0123456789-.,;:_<>');
}

public function iv() {
return mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
}
}

And on test.php, following code:

<?
require('Auth.php');
$Auth = new Auth;

$str = "verygudlongpassword";

for ($i = 0; $i < 1000; $i++) {
    $salt = sha1($Auth->salt());
    $iv = $Auth->iv();

    $enc = $Auth->aes_enc($str, $salt, $iv);
    $dec = $Auth->aes_dec($enc, $salt, $iv);

    if ($str != $dec) {
        echo $salt . "<br>\n";
    }
}
?>

Sometimes, $dec != $str. Why is this happening? I am not even saving anything into DB atm, so it's not that. Thanks for help.

i dont really have anything more to say, but site isnt letting me post. (nvm that part)


Solution

  • After reviewing your code and playing with it locally. It would appear that your decryption leaves some whitespace on the decrypted text. I removed the trim() function from all locations except the return value from aes_dec() and the code now encrypts/decrypts your string successfully 1000 times.

    So it would seem trimming was the problem and the solution.

    class Auth extends MySQLi {
        public function aes_enc($encrypt, $mc_key, $iv)
        {
            $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), $encrypt, MCRYPT_MODE_CBC, $iv);
            return $passcrypt;
        }
    
        public function aes_dec($decrypt, $mc_key, $iv)
        {
            $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), $decrypt, MCRYPT_MODE_CBC, $iv));
            return $decrypted;
    
        }
    
        public function salt()
        {
            return str_shuffle('abcdefghijklmnoprsquvzyx0123456789-.,;:_<>');
        }
    
        public function iv()
        {
            return mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
        }
    }
    
    $Auth = new Auth;
    
    $str = "verygudlongpassword";
    
    for ($i = 0; $i < 1000; $i++) {
        $salt = sha1($Auth->salt());
        $iv = $Auth->iv();
    
        $enc = $Auth->aes_enc($str, $salt, $iv);
        $dec = $Auth->aes_dec($enc, $salt, $iv);
    
        if ($str != $dec) {
            echo "Decryption failed!<br>\n";
        } else {
            echo "Decryption success! String: $dec<br>\n";
        }
    }