Question

Using PHP I'm trying to convert the cipher text generated by mcrypt into binary but when I try and convert it back to the cipher text it doesnt get converted back properly so it cant be decrypted. I'm assuming my encodings are getting messed up somewhere but I dont know where to start to figure it out. Here is a link to the site http://dev.hersha.me/str2bin.php and here is my code.

<?php

class phpSteg {

function bin2bstr($input) {
    if (!is_string($input)) return null;
    return pack('H*', base_convert($input, 2, 16)); 
}

function bstr2bin($input) {
    if (!is_string($input)) return null;
    $value = unpack('H*', $input);
    return base_convert($value[1], 16, 2);
}


};

$steg = new phpSteg();

//echo $steg->bstr2bin('OMG') . "\n <br \>";
//echo $steg->bin2bstr('010011110100110101000111') . "\n <br \>";
$hash =  hash('md5',"OMGZWTF");
echo $hash . "\n <br \>";
$message = "OMG WTF BBQ";

$text = $message;
$key = $hash;

$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_RAND);
echo $iv . "\n <br \>";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CFB, $iv);

$binenc = $steg->bstr2bin($encrypted);

$bstrenc = $steg->bin2bstr($binenc);


$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $bstrenc, MCRYPT_MODE_CFB, $iv);
echo "Cipher Text : " . $encrypted . "\n <br \>";

echo "Cipher Text (binary) : " . $binenc . "\n <br \>";

echo "Cipher Text (back from binary) : " . $bstrenc . "\n <br \>";

echo "Decryption : " . $decrypted; // The quick brown fox jumps over the lazy dog

?>

Any ideas?

Was it helpful?

Solution 3

All issues solved.

First: I was overloading the base_convert function. Needed smaller data set.

Second: Rather simple and obvious really, base_convert ignores leading zeros, so when converting had to add them back.

OTHER TIPS

Do not bother using bin2bstr and bstr2bin. If you need to store the string somewhere (like a database) just base64 encode/decode the string after encryption.

$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CFB, $iv);

$binenc = base64_encode($encrypted);

$bstrenc = base64_decode($binenc);

$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $bstrenc, MCRYPT_MODE_CFB, $iv);

Try base64_encode on your binary string before encrypting, and use base64_decode after it's decrypted. Mcrypt might be choking on the data otherwise, without letting you know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top