bin2hex / hex2bin help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bdeverea
Forum Newbie
Posts: 2
Joined: Wed Aug 25, 2004 11:07 am

bin2hex / hex2bin help

Post 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
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post 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
bdeverea
Forum Newbie
Posts: 2
Joined: Wed Aug 25, 2004 11:07 am

Post 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!
Post Reply