Suhab Safy
Suhab Safy

Reputation: 13

How to decrypt encrypted string?

I almost lost my mind trying to reverse this function, a friend of mine suggested to ask "the pros" so I am here.

<?php
$data = "Data to be encrypted";
$ceva = $data;
$textHos = 'MCRYPT_RIJNDAEL_128';
function encrypt($plaintext,$textHos) {
    $textLen=str_pad(dechex(strlen($plaintext)),8, '0', STR_PAD_LEFT);
    $salt='WSj2g7jTvc8ISmL60Akn';
    $textHosHash=hash('sha256',$salt.$textHos);
    $textHos= md5($textHos,true);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);  
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $textHos,
                                 $plaintext, MCRYPT_MODE_CBC,$iv);

    $ciphertext = $iv . $textHosHash . $textLen . $ciphertext;
    $ciphertext_base64 = base64_encode($ciphertext);
    return  $ciphertext_base64;
}
$data = encrypt($ceva,$textHos);
echo $data;
?>

The output is:

P8avDeviXdd7bKfNMP0gwmZmZjg1OWMzOWFlNzRiMzU2Y2JiMTQ5OTY4MTI3MWNiYjQzYjBkMTAyNDUzM2ZhNGJjZmZhNzQ4M2QxN2M0ZGYwMDAwMDAxNN2xStdw/bhxIxSOevRp37HiXJeVXz7Ge31KEvq9dZjT

any help with resolving the encrypted text into a readable one again? Thanks.

Upvotes: 0

Views: 97

Answers (1)

Philipp
Philipp

Reputation: 15629

Your encrypt function makes a lot of nonsense and I hope it doesn't run in any production environment.

function encrypt($plaintext,$textHos) {
    // not needed..
    //$textLen=str_pad(dechex(strlen($plaintext)),8, '0', STR_PAD_LEFT);
    //$salt='WSj2g7jTvc8ISmL60Akn';
    //$textHosHash=hash('sha256',$salt.$textHos);

    $textHos = md5($textHos,true);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);  
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $textHos,
                                 $plaintext, MCRYPT_MODE_CBC,$iv);

    // i commented out the unneccessary parts..
    $ciphertext = $iv /* . $textHosHash . $textLen . */ $ciphertext;
    $ciphertext_base64 = base64_encode($ciphertext);
    return $ciphertext_base64;
}

So whats left in the encrypted data is the iv vector (and 72 chars of some unneccessary data) and the encrypted data itself - encoded in base64

Reversing this is quite easy

function decrypt($ciphertext, $textHos) {
    $text = base64_decode($ciphertext);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = substr($text, 0, $iv_size);
    $textHos = md5($textHos, true);
    // the +72 is neccessary for your original code - the code above doesn't need this part
    $ciphertext = substr($text, $iv_size + 72);
    $encrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $textHos, $ciphertext, MCRYPT_MODE_CBC, $iv);
    return rtrim($encrypted, chr(0));
}

Note: DON'T USE THIS CODE IN PRODUCTION! Nowdays AES128 isn't safe

Upvotes: 1

Related Questions