Search code examples
phpdecodeencodemcrypt

PHP Mcrypt and Base64 encode decode return strange characters


I have used the following to encode and decode a simple string "abcdefg123"

function encryptIt( $q ) {
    $cryptKey  = 'fkEir8eu0ajiOo93q32txY';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return( $qEncoded );
}

function decryptIt( $q ) {
    $cryptKey  = 'fkEir8eu0ajiOo93q32txY';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return( $qDecoded );
}

I get encoded A/ziTyvagw4vgKbIOOdvP1zy15p0mkY6hIYSJcE2Kq4= but decoded returns 8��M�j�3l0�q��M�#�蟂T��@�mҾQ

I have read the other solutions here at stackoverflow like utf8_decode() and rawurlencode(), but still can't seems to get it to work. I am using php 7.


Solution

  • Try this....

    define('ENCRYPTION_KEY', md5("fkEir8eu0ajiOo93q32txY"));
    // Encrypt Function
    function mc_encrypt($encrypt, $key){
        $encrypt = serialize($encrypt);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
        $key = pack('H*', $key);
        $mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32));
        $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt.$mac, MCRYPT_MODE_CBC, $iv);
        $encoded = base64_encode($passcrypt).'|'.base64_encode($iv);
        return $encoded;
    }
    // Decrypt Function
    function mc_decrypt($decrypt, $key){
        $decrypt = explode('|', $decrypt.'|');
        $decoded = base64_decode($decrypt[0]);
        $iv = base64_decode($decrypt[1]);
        if(strlen($iv)!==mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)){ return false; }
        $key = pack('H*', $key);
        $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv));
        $mac = substr($decrypted, -64);
        $decrypted = substr($decrypted, 0, -64);
        $calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32));
        if($calcmac!==$mac){ return false; }
        $decrypted = unserialize($decrypted);
        return $decrypted;
    }
    $data = 'abcdefg123';
    $encrypted_data = mc_encrypt($data, ENCRYPTION_KEY);
    echo 'Data to be Encrypted: ' . $data . '<br/>';
    echo 'Encrypted Data: ' . $encrypted_data . '<br/>';
    echo 'Decrypted Data: ' . mc_decrypt($encrypted_data, ENCRYPTION_KEY) . '</br>';