Dieter Profos
Dieter Profos

Reputation: 57

PHP: input string for md5 (and sha1) must be purely alphanumeric?

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?

Upvotes: 0

Views: 610

Answers (1)

LSerni
LSerni

Reputation: 57398

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?

Upvotes: 4

Related Questions