Page 1 of 1

bin2hex / hex2bin help

Posted: Wed Aug 25, 2004 11:07 am
by bdeverea
I'm building a system which will allow me to encrypt and store data in a MySQL DB. The encrypting and decrypting parts I have no problems with, however in order to store the number in the DB I need to perform a bin2hex conversion.

I am using a hex2bin function that I found somewhere on PHP Builder, to convert the stored, encrypted number back to hex, however when I perform these functions I am only getting half of the number converted (the first 8 characters). I am posting the code, any guidance or help is greatly appreciated.

Code: Select all

<?php
//convert hex string to binary string (used in decrypt_data) 
function hex2bin($data) { 
    $len = strlen($data); 
    for($i=0;$i<$len;$i+=2) { 
        $newdata .= pack("C",hexdec(substr($data,$i,2))); 
    } 
    return $newdata; 
}
?>

thanks

Posted: Wed Aug 25, 2004 12:02 pm
by scorphus
It seems to be working:

Code: Select all

<?php
function hex2bin($data) {
	$len = strlen($data);
	$newdata = '';
	for($i=0;$i<$len;$i+=2) {
		$newdata .= pack("C",hexdec(substr($data,$i,2)));
	}
	return $newdata;
}

$str = "Test bit of string!";
$hexstr = bin2hex($str);
echo hex2bin($hexstr) . "\n";
echo pack("H*", $hexstr) . "\n";// maybe a simpler way
?>
output:

Code: Select all

Test bit of string!
Test bit of string!
-- Scorphus

Posted: Wed Aug 25, 2004 12:43 pm
by bdeverea
Thanks for the quick reply scorphus. You're right, the hex2bin function seems to be working properly. I guess the error must be occurring during either my encrypt or decrypt functions.

I'm a bit cautious about posting my encrypt/decrypt codes but if anyone had any ideas why only the first 8 characters of a 16 character string are being decrypted properly I'm very open to ideas.

Thanks!