0

Using the PHP functions md5() (and sha1() as well) with a string like 'aabbccdd' works perfectly. However, using the same functions with 'a-b+ccdd' doesn't seem to produce a consistent result.

First question: Has the input string to be strictly alphanumeric, i.e. [A-Z][a-z][0..9] ?

Second question: Why do I get entirely different results using two different php files as follows:

file 1:

<?php
  $pwd = $_GET['pwd'];
  echo sha1($pwd); 
?>

and file 2 (only its beginning):

<?php session_start(); 

  $username = $_POST["username"];
  $pass = $_POST["password"];
  $password = sha1($pass); 

  echo "<br>pwd = " . $pass . "<br>PWD(SHA1) = " . $password . "<br>";

Does anyone see what's going wrong?

1 Answers1

4

MD5 will gladly take any input you like.

You are hitting a different problem: some characters will be encoded when sent via URL, so that for example "+" will be taken as signifying space (" "), and so on.

In other words, you send a-b+cc, but the receiving PHP script will 'see' a-b cc, and the output from md5() will therefore be different from what you expect.

You will have either to encode the string before, or decode them afterwards taking into account that they might have been incorrectly encoded, before feeding it to md5(). This second option is much more awkward (you receive a " ", and won't know whether it was a space or a plus sign!); so, unless there is absolutely no other way, try to properly encode the strings before sending. See for example: Encode URL in JavaScript?

Community
  • 1
  • 1
LSerni
  • 55,617
  • 10
  • 65
  • 107
  • 3
    Reading from `$_POST/GET/REQUEST` will properly decode them. It's just the encoding before making the request that needs to be done right. – Quentin Jan 22 '13 at 14:21
  • Right, I'll rephrase the answer. Thanks – LSerni Jan 22 '13 at 14:23
  • Many thanks for the valuable hint. However, I'm not sure that this is really the reason: As you may see above, I did echo the clear password before encrypting it, and it looked correct, including the + sign. Since PHP is using ANSI, should I encode the string in ANSI/ISO-8859-1 before sending it? – Dieter Profos Jan 22 '13 at 19:35
  • You might also have some problem with UTF8 (or, who knows?, extra whitespaces). I'd save the password to a disk file in the same script receiving the POST, and then examine the file with a hex editor, in order to be really sure of its content (whitespaces, carriage returns, other "invisible" characters, and encoding problems). – LSerni Jan 22 '13 at 21:58