0

Here is my encode url param aKVXt4_P78X64w5ApVAZJ0fSNpV_GGFWxBs0aE_xw_24ghq1C5awAAPPKYbZSi0rGJUmyPlohVsP0fE4-jHQnN

When Encryption class decode it the result is ±­�ыП^ґрьI§эЁ¶шЪ™МkVЃ°(ѓ7m‰e+и *“V«;Ё@ЧB§Z{Ћ‹JЈи_ЈWfUѕe

I don't understand the reason of such issue, it happens rather rarely but brings some trouble.

To uncode/decode links i use such class.

class Encryption {
// config local ENCRIPTION_KEY
var $skey = ENCRIPTION_KEY; 

private function safe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

private function safe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

public  function encode($value){
    if(!$value){return false;}
    $text = $value;
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypttext = trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, trim($text), MCRYPT_MODE_ECB, $iv));
    return trim($this->safe_b64encode($crypttext));
}

public function decode($value){
    if(!$value){return false;}
    $crypttext = $this->safe_b64decode($value);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
    return trim($decrypttext);
}
}
Inisheer
  • 20,376
  • 9
  • 50
  • 82
Anton Sementsov
  • 1,196
  • 6
  • 18
  • 34

1 Answers1

1

I believe the problem you are having is that you are encrypting using a random IV and then trying to decrypt using a completely different random IV. It is important to have a random IV, but you need the same IV to decrypt. The IV does not need to be secret as long as the constant KEY is hidden.

Also @Daniel was correct when saying that ECB doesn't use an IV. It will ignore it, so the last paragraph is now mute. However, you should consider switching from ECB to CBC as it is more secure (simply because it does use an IV).

I wrote a small class to encrypt/decrypt using MCRYPT in CBC mode (allowing any supported encryption algorithm e.g., BLOWFISH, TWOFISH, RIJNDAEL, etc). When encrypting it creates a random IV then prepends it to the encrypted string before returning the whole lot in hex. Then when it needs to decrypt the same string it will convert back to bin, determine the iv size of the encryption algorithm, remove the IV from the encrypted string and use it to return the decrypted string. If you think it might help, you can check it out. Hope it helps.

Adrian Trainor
  • 267
  • 1
  • 9