This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
darkrising's profile picture

[Solved] [Lua] [PHP] Matching hash Sha1

Started by darkrising, 27 June 2013 - 02:20 PM
darkrising #1
Posted 27 June 2013 - 04:20 PM
Hello, I've been playing with sha1 hashing and can't seem to generate a hash match with the same data:

Heres my code:
Lua:
Spoiler

function send(stuff)
  server = "http://127.0.0.1/cc/test.php"
  response = http.post(server, "test=" .. stuff)
  content = response.readAll()
  response.close()
  content = textutils.unserialize(content)
  return content.salt , content.hash
end
function get(str, salt, hash)
  server = "http://127.0.0.1/cc/test.php"
  response = http.post(server,
	"t=true" .. "&" ..
	"hash=" .. hash .. "&" ..
	"salt=" .. salt
  )
  content = response.readAll()
  response.close()
  print(content)
end

test = "apple"
salt, hash = send(test)
print(salt)
print(hash)
get(test, salt, hash)

PHP:
Spoiler


<?php
function generateRandomString($length = 10) {
	$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$randomString = '';
	for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[rand(0, strlen($characters) - 1)];
	}
	return $randomString;
}

  if (isset($_POST['test'])) {
	$str = $_POST['test'];
	$salt = generateRandomString(10);
	$fash = sha1($str . $salt);
	echo "{
	  [\"salt\"] = \"$salt\",
	  [\"hash\"] = \"$fash\",
	}";
  };

  if (isset($_POST['t'])) {
	$str = $_POST['t'];
	$hash = $_POST['hash'];
	$salt = $_POST['salt'];
	$fash = sha1($str . $salt);

	echo
	  "\n" .
	  "Fash $fash \n" .
	  "Hash $hash \n"	
	;

	if ($fash == $hash) {
	  echo "Match!";
	}else{
	  echo "No match!";
	};
  };
?>

Most likely the salt would be stored somewhere on the PHP side, maybe a MySql database but for testing purposes this should work…

(The reason I'm doing this through PHP is a learning curve, I would very much like CC and PHP to play nice together as I have some cool ideas.)
darkrising #2
Posted 28 June 2013 - 05:20 AM
I just realised what I did wrong:

Line 12 should be:
"t=" .. str .. "&amp;" ..

Solved!