views:

41

answers:

2

Ok, so I'm trying to figure out how to go from hexadecimal encryption to string and back, but for some reason the when I encrypt, i'm not getting the same password that was passed in, but its close...weird right? I'm sure my syntax is wrong somewhere. Help?

Here's a link to test a little random password. I've set 'pw' as the hexadecimal version and pass that in: view demo

$encoded  = (string)$_GET['pw'];  
$literals = explode(' ', wordwrap($encoded, 2, ' ', 2));  
$password = '';  

for ($i = 0; $i < count($literals); $i++) {  
    $password .= chr(hexdec($literals[$i]) - $i);  
}

echo $password . '<br />';
print_r($literals) . '<br />';
$passarray = str_split($password);

echo '<pre>';
print_r($passarray);
echo '</pre>';

for($i = 0; $i < count($passarray); $i++) {
    $newpassword .= bin2hex($passarray[$i]);
}
echo $newpassword;

UPDATE:

.I'm actually not trying to "encrypt" for security per se...I'm actually trying to automate the creation of Dreamweaver Site Definition files and this is the "encryption" they use to semi-hide the password. I can do this already by copying the file and inserting different usernames, but I'd like to issue and new password each time as well. just FYI

+3  A: 

Look closer at this line:

$password .= chr(hexdec($literals[$i]) - $i);

You're decreasing the value by $i. So every increment, the value will be $literals[$i] - $i.

This is the reverse of the above:

$newpassword .= dechex(ord($passarray[$i]) + $i);
Lekensteyn
well, that part actually works. that line decodes the hexadecimal password and prints it (see demo). The problem is going back to hexadecimal once I have the string.
d2burke
Perfect! Did edit to add that last line in? I must have missed it! Thanks Lek
d2burke
A: 

Hexadecimal isn't an encryption, but an encoding at best (it's mostly a number base in fact). It looks like you're mixing up the base conversion, and the hexadecimal encoding of the character encoding itself.

  • hexdec will turn 0, 1, 9, A, F, 10 into 0, 1, 9, 10, 15, 16, respectively.
  • chr will turn the decimal number into a character (using the ASCII character encoding)
  • Not sure why you're substracting $i in the value you got.
  • On the other side, bin2hex effectively gives you an hexadecimal representation of a binary sequence of data (at least so that it can be printed out). It's not necessarily the opposite of chr(hexdec(...)).

Overall, it's not clear what kind of password protection you're trying to achieve here, since it's just encoding.

Bruno