« Ritorna al blog

Ritorna alla lista completa degli articoli

Mettiti alla prova: hashing delle password in un file di testo

PHP - SFIDE - febbraio 08, 2022

In questo esercizio si dovrà creare un file di testo dove sarà riportato username e password di un utente. La username sarà scritta in chiaro mentre la password attraverso un algoritmo avanzato di criptazione. In PHP abbiamo la comodissima funzione denominata password hash(). Nella pagina start.php si dovranno inserire almeno quattro account e verificare che la password venga criptata correttamente. Si dovrà controllare che:

  • I campi del form vengano tutti completati;
  • la username dovrà essere minuscola, senza spazi e senza virgola.

In questo esercizio tralasciamo volutamente il controllo sulla sicurezza di una password.

start.php

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Hash password</title>

	<!-- Bootstrap CSS -->
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
</head>

<body>

	<?php

	global $msg;

	if ($_SERVER["REQUEST_METHOD"] == "GET") {
		if (isset($_GET["msg"]) && $_GET["msg"] == "success") {

			$msg = '<div class="alert alert-dismissible alert-success">';
			$msg .= '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
			$msg .= '<strong>Ben fatto!</strong> Il file è stato creato correttamente.';
			$msg .= '</div>';
		}

		if (isset($_GET["msg"]) && $_GET["msg"] == "error") {

			$msg = '<div class="alert alert-dismissible alert-danger">';
			$msg .= '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
			$msg .= '<strong>Attenzione!</strong> Errore nell\'invio dei dati. Prova a completare tutti i campi. Grazie';
			$msg .= '</div>';
		}
	}


	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		if (isset($_POST["btn_hash_password"])) {
			
			// Risultato dell'operazione
			$result = "";

			// da completare e correggere
			if (false) {
				$result = "success";
			} else {
				$result = "error";
			}

			// Redirect
			if (!empty($result)) {
				header("location:" . $_SERVER["PHP_SELF"] . "?msg=" . $result);
				exit();
			}
		}
	}
	?>



	<div class="container">
		<div class="row">
			<div class="col-8 mx-auto">
				<div class="py-5 text-center">
					<h2>Hash delle password</h2>
					<p class="lead">Account da convertire</p>
					<?php echo $msg; ?>
				</div>
			</div>
			<div class="col-md-8 mx-auto">
				<form id="form1" name="form1" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" class="mt-4 mb-4">
					<fieldset>
						<legend>Elenco</legend>

						<!-- Creo 5 campi di testo -->
						<?php for ($f = 1; $f <= 4; $f++) : ?>
							<div class="row mb-2 p-3 bg-light border rounded-3">
								<div class="form-group col-md-6">
									<label for="free_password"><?php echo $f; ?> - Username</label>
									<input type="text" class="form-control" id="username_<?php echo $f; ?>" name="username[]" />
								</div>
								<div class="form-group col-md-6">
									<label for="free_password"><?php echo $f; ?> - Password</label>
									<input type="password" class="form-control" id="password_<?php echo $f; ?>" name="password[]" />
								</div>
							</div>
						<?php endfor ?>

						<div class="form-group mt-4">
							<button type="submit" name="btn_hash_password" class="btn btn-primary w-100">Converti</button>
						</div>
					</fieldset>
				</form>
			</div>
		</div>

	</div>


	<!-- Bootstrap Bundle with Popper -->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>

Per risolvere l'esercizio basterà ragionare sulle seguenti funzioni incorporate del PHP:

Il file di testo, che si andrà  a generare, dovrà contenere una formattazione simile alla seguente:

gianfrancopercopo,$2y$10$dJ8CoFZXh2mBa14k0A3rveX6Nt5i3U0.YXXRNoE8zlujPU6OI5Q4y
mariorossi,$2y$10$EBBdrs3pgAmN6HOa1CEX9uHb1/pm2G/CGec68K4mIxKChVc1Ssp.a

Buon lavoro e soprattutto divertitevi :)

finish.php

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Hash password</title>

	<!-- Bootstrap CSS -->
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
</head>

<body>

	<?php

	global $msg;

	if ($_SERVER["REQUEST_METHOD"] == "GET") {
		if (isset($_GET["msg"]) && $_GET["msg"] == "success") {

			$msg = '<div class="alert alert-dismissible alert-success">';
			$msg .= '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
			$msg .= '<strong>Ben fatto!</strong> Il file è stato creato correttamente.';
			$msg .= '</div>';
		}

		if (isset($_GET["msg"]) && $_GET["msg"] == "error") {

			$msg = '<div class="alert alert-dismissible alert-danger">';
			$msg .= '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
			$msg .= '<strong>Attenzione!</strong> Errore nell\'invio dei dati. Prova a completare tutti i campi. Grazie';
			$msg .= '</div>';
		}
	}


	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		if (isset($_POST["btn_hash_password"])) {
			
			// Risultato dell'operazione
			$result = "";

			// da completare e correggere
			$arr_username = !empty($_POST["username"]) ? $_POST["username"] : array();
			$arr_password = !empty($_POST["password"]) ? $_POST["password"] : array();
			$arr_text = array();

			if (
				sizeof($arr_username) == sizeof($arr_password) &&
				(!in_array("", $arr_username) && !in_array("", $arr_password))
			) {
				for ($c = 0; $c < sizeof($arr_username); $c++) {

					$username = trim($arr_username[$c]);
					$username = str_replace(",", "", $username);
					$username = str_replace(" ", "", $username);
					$username = strtolower($username);

					$password = trim($arr_password[$c]);
					$password = password_hash($password, PASSWORD_DEFAULT);

					$item = $username . "," . $password;
					array_push($arr_text, $item);
				}

				// Scrivo il file
				$myfile = fopen("file/password_hash.txt", "w") or die("Impossibile scrivere il file!");
				foreach ($arr_text as $item) {
					$txt = $item . "\n";
					fwrite($myfile, $txt);
				}
				fclose($myfile);

				$result = "success";
			} else {
				$result = "error";
			}

			// Redirect
			if (!empty($result)) {
				header("location:" . $_SERVER["PHP_SELF"] . "?msg=" . $result);
				exit();
			}
		}
	}
	?>



	<div class="container">
		<div class="row">
			<div class="col-8 mx-auto">
				<div class="py-5 text-center">
					<h2>Hash delle password</h2>
					<p class="lead">Account da convertire</p>
					<?php echo $msg; ?>
				</div>
			</div>
			<div class="col-md-8 mx-auto">
				<form id="form1" name="form1" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" class="mt-4 mb-4">
					<fieldset>
						<legend>Elenco</legend>

						<!-- Creo 5 campi di testo -->
						<?php for ($f = 1; $f <= 4; $f++) : ?>
							<div class="row mb-2 p-3 bg-light border rounded-3">
								<div class="form-group col-md-6">
									<label for="free_password"><?php echo $f; ?> - Username</label>
									<input type="text" class="form-control" id="username_<?php echo $f; ?>" name="username[]" />
								</div>
								<div class="form-group col-md-6">
									<label for="free_password"><?php echo $f; ?> - Password</label>
									<input type="password" class="form-control" id="password_<?php echo $f; ?>" name="password[]" />
								</div>
							</div>
						<?php endfor ?>

						<div class="form-group mt-4">
							<button type="submit" name="btn_hash_password" class="btn btn-primary w-100">Converti</button>
						</div>
					</fieldset>
				</form>
			</div>
		</div>

	</div>


	<!-- Bootstrap Bundle with Popper -->
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>
Mettiti alla prova: hashing delle password in un file di testo
Mettiti alla prova: hashing delle password in un file di testo
Mettiti alla prova: hashing delle password in un file di testo
Mettiti alla prova: hashing delle password in un file di testo