0

i have a little problem: my decryption won't give me the same string i encoded, and i can't find the problem... looked in other posts, but nothing helpful there here are my functions:

public static function encryptData($data){
    if($key = self::getEncryptionKey()){
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_ECB,$iv));
    } else {
        return false;
    }
}

public static function decryptData($data)
{
    if($key = self::getEncryptionKey()){
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($data), MCRYPT_MODE_ECB,$iv);
    } else {
        return false;
    }

}

where's the problem? i'm kinda desperate here...

3
  • 1
    Perhaps you should use mcrypt_decrypt to decrypt data - or is this just a copy&paste-mistake? Commented Nov 21, 2011 at 16:56
  • +1 for using mcrypt_decrypt. @AlexK: Have you seen/tried phpseclib.sourceforge.net? Commented Nov 21, 2011 at 16:59
  • that's a copy/paste mistake... but i just figured out the problem, he didn't like blanks... Commented Nov 21, 2011 at 17:00

1 Answer 1

1

To decrypt you need everything exactly the same at both sides. key, mode, IV and padding.

Looking at your code, you appear to be generating a new IV for decryption. Don't. Use the same IV as you used to encrypt.

You, correctly, specify a mode explicitly, but you pick the worst possible mode. Don't use ECB, it leaks information. Use CBC or CTR mode instead.

You don't specify a padding. Far better to specify it explicitly, use PKCS7 with Rijndael.

If none of that helps, then check your key, byte by byte, to make sure it is the same for both encryption and decryption.

Sign up to request clarification or add additional context in comments.

2 Comments

you are right, ECB should be avoided, but whatever he supplies as IV shouldn't make any difference here
That's the second time in so many days that I've seen an issue with PHP, ECB & IV vector involved. Are we sure that IV is not included in the calculation of the first block? Can somebody check?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.